这篇文章主要介绍了python如何删除文件夹的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python如何删除文件夹文章都会有所收获,下面我们一起来看看吧。
具体操作方法:
1、首先需要在python脚本中导入os模块进行文件操作。
import os
2、再if语句判断需要删除的文件夹是否为空。
3、最后使用os.listdir()方法获取空的文件夹并通过rmdir函数进行删除文件夹即可。
代码示例如下:
#!/usr/bin/pythonimport os# getting the folder path from the userfolder_path = input("Enter folder path:- ")# checking whether folder exists or notif os.path.exists(folder_path):# checking whether the folder is empty or notif len(os.listdir(folder_path)) == 0:# removing the file using the os.remove() methodos.rmdir(folder_path)else:# messaging saying folder not emptyprint("Folder is not empty")else:# file not found messageprint("File not found in the directory")
相关函数:
os.remove #删除文件os.rmdir #删除文件夹shutil.rmtree #删除目录及其所有内容
关于“python如何删除文件夹”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python如何删除文件夹”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/szz715/blog/4429533