如何删除文件夹中的内容?

新手上路,请多包涵

如何删除 Python 中本地文件夹的内容?

当前项目适用于 Windows,但我也希望看到 *nix。

原文由 UnkwnTech 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 247
2 个回答
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))

原文由 Nick Stinemates 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以简单地这样做:

 import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)

您当然可以在路径中使用其他过滤器,例如:/YOU/PATH/*.txt 用于删除目录中的所有文本文件。

原文由 Blueicefield 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题