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

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


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


RISEBY
浏览 1569回答 3
3回答

慕少森

已更新为仅删除文件并使用os.path.join()了注释中建议的方法。如果您还想删除子目录,请取消注释该elif语句。import os, shutilfolder = '/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)

有只小跳蛙

试试shutil模块import shutilshutil.rmtree('/path/to/folder')描述: shutil.rmtree(path, ignore_errors=False, onerror=None)Docstring:递归删除目录树。如果ignore_errors设置了,将忽略错误;否则,如果onerror设置,它被称为处理与参数的误差(func, path, exc_info)在那里  func为os.listdir,os.remove或  os.rmdir; path是导致该函数失败的参数。并且  exc_info是由返回的元组  sys.exc_info()。如果ignore_errors为false和onerroris None,则会引发异常。重要说明:请注意,shutil.rmtree()这不仅会删除目标文件夹的内容。它还会删除文件夹本身。

慕尼黑8549860

扩展mhawke的答案,这就是我已经实现的方法。它会删除文件夹的所有内容,但不会删除文件夹本身。在Linux上经过测试,带有文件,文件夹和符号链接,也应该在Windows上运行。import osimport shutilfor root, dirs, files in os.walk('/path/to/folder'):    for f in files:        os.unlink(os.path.join(root, f))    for d in dirs:        shutil.rmtree(os.path.join(root, d))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python