删除Python中的文件夹内容 [英] Delete Folder Contents in Python
本文介绍了删除Python中的文件夹内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中删除本地文件夹的内容?
How can I delete the contents of a local folder in Python?
当前项目是Windows,但我也想看到* nix。 >
The current project is for Windows but I would like to see *nix also.
推荐答案
更新为仅删除文件并使用注释中建议的os.path.join()方法。如果还要删除子目录,请取消注释elif语句。
Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement.
import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
这篇关于删除Python中的文件夹内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文