为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

RISEBY 2019-10-24 10:00:37
如何在Python中删除本地文件夹的内容?当前项目适用于Windows,但我也希望看到* nix。
查看完整描述

3 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

已更新为仅删除文件并使用os.path.join()了注释中建议的方法。如果您还想删除子目录,请取消注释该elif语句。


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)


查看完整回答
反对 回复 2019-10-24
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

试试shutil模块


import shutil

shutil.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()这不仅会删除目标文件夹的内容。它还会删除文件夹本身。


查看完整回答
反对 回复 2019-10-24
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

扩展mhawke的答案,这就是我已经实现的方法。它会删除文件夹的所有内容,但不会删除文件夹本身。在Linux上经过测试,带有文件,文件夹和符号链接,也应该在Windows上运行。


import os

import shutil


for 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))


查看完整回答
反对 回复 2019-10-24
  • 3 回答
  • 0 关注
  • 1574 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信