python如何删除文件夹
更新:HHH   时间:2023-1-7


这篇文章主要介绍了python如何删除文件夹的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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 #删除目录及其所有内容


关于“python如何删除文件夹”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python如何删除文件夹”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注天达云行业资讯频道。

返回大数据教程...