【问题标题】:How to remove a lot of folders at once using Python?如何使用 Python 一次删除大量文件夹?
【发布时间】:2016-02-24 16:54:45
【问题描述】:

我看到很多问题(Delete Folder Contents in PythonHow to delete a file or folder?How do I remove/delete a folder that is not empty with Python?)询问如何删除文件夹(是否为空),但我没有看到任何有关如何删除大量文件夹的问题文件夹。

我尝试使用shutils 并写成shutils.rmtree('.../run*')(我要删除的所有文件夹都称为run0000、run0001 等)但这不起作用,因为* 不被理解。

我最终导入了子进程并使用了subprocess.Popen('rm -r ./run*/', shell=True),因为shell=True 有效,但我想避免这种情况,因为与安全相关的危险不鼓励使用shell=True

一次擦除大量文件夹(非空)的最佳方法是什么?我认为必须调整其中一个链接问题中给出的一些答案,但到目前为止我还没有做到。我该怎么办?

【问题讨论】:

    标签: python python-2.7 shell


    【解决方案1】:

    您可以使用glob module 定位目录,然后在每个目录上使用shutil.rmtree()

    from glob import iglob
    import shutil
    
    for path in iglob('.../run*'):
        shutil.rmtree(path)
    

    因为您不需要所有匹配目录的完整列表,所以我使用glob.iglob() 来一一生成匹配的路径。

    【讨论】:

      猜你喜欢
      • 2016-12-26
      • 2011-12-26
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2011-10-20
      • 2016-03-29
      • 1970-01-01
      • 2022-10-18
      相关资源
      最近更新 更多