python

python怎么删除文件夹

摘星
659
2021-05-26 11:22:01
栏目: 编程语言

python中删除文件夹的方法:1、在python脚本中导入os模块;2、使用if语句判断文件夹是否为空;3、最后使用os.listdir()方法获取空文件夹并通过rmdir函数进行删除文件夹即可。

python怎么删除文件夹

具体操作方法:

1、首先需要在python脚本中导入os模块进行文件操作。

import os

2、再if语句判断需要删除的文件夹是否为空。

3、最后使用os.listdir()方法获取空的文件夹并通过rmdir函数进行删除文件夹即可。

代码示例如下:

#!/usr/bin/python

import os

# getting the folder path from the user

folder_path = input("Enter folder path:- ")

# checking whether folder exists or not

if os.path.exists(folder_path):

# checking whether the folder is empty or not

if len(os.listdir(folder_path)) == 0:

# removing the file using the os.remove() method

os.rmdir(folder_path)

else:

# messaging saying folder not empty

print("Folder is not empty")

else:

# file not found message

print("File not found in the directory")

相关函数:

os.remove #删除文件

os.rmdir #删除文件夹

shutil.rmtree #删除目录及其所有内容

0
看了该问题的人还看了