【问题标题】:How to remove a directory including all its files in python?如何删除一个目录,包括它在python中的所有文件?
【发布时间】:2017-05-03 09:34:26
【问题描述】:

我正在编写一些 Python 代码。我想在程序结束时删除new_folder,包括它的所有文件。

有人可以指导我如何做到这一点吗?我见过像 os.rmdir 这样的不同命令,但它只删除了路径。这是我的代码:

for files in sorted(os.listdir(path)):
  os.system("mv "+path+" new_folder")`

上面的代码会将一个文件夹(称为检查)移动到 new_folder。我想从 new_folder 中删除该检查文件夹。

【问题讨论】:

标签: python python-2.7


【解决方案1】:

如果要删除文件

import os
os.remove("path_to_file")

但是如果你想删除目录,你不能使用上面的代码删除目录然后使用这个

import os
os.rmdir("path_to_dir")

从上面的命令中,如果目录不为空,则可以删除目录,如果目录不为空,则可以使用shutil模块

import shutil
shutil.rmtree("path_to_dir")

以上所有方法都是 Python 方法,如果您了解您的操作系统,则此方法依赖于操作系统,所有上述方法都不依赖

import os
os.system("rm -rf _path_to_dir")

【讨论】:

    【解决方案2】:

    只需使用shutil.rmtree

    import shutil
    shutil.rmtree(path)
    

    【讨论】:

      【解决方案3】:

      使用os.system("rm -rf" + whatever_path +" new_folder")

      【讨论】:

      • 但我想删除另一个文件夹中的文件夹。
      • 我想使用类似的东西。如果 os.path.exists() 然后删除
      • 使用 os.system("rm -rf" + path + "/new_folder")。此外,如果文件夹不存在,那么 -f 函数不会抛出错误,因此您已经设置好了
      • 最好使用其他答案中建议的shutil.rmtree。如果字符串 whatever_path 来自不受信任的输入,则此答案打开了执行任意 shell 命令的可能性。
      【解决方案4】:

      这是我的方法:

      # function that deletes all files and then folder
      
      import glob, os
      
      def del_folder(dir_name):
          
          dir_path = os.getcwd() +  "\{}".format(dir_name)
          try:
              os.rmdir(dir_path)  # remove the folder
          except:
              print("OSError")   # couldn't remove the folder because we have files inside it
          finally:
              # now iterate through files in that folder and delete them one by one and delete the folder at the end
              try:
                  for filepath in os.listdir(dir_path):
                      os.remove(dir_path +  "\{}".format(filepath))
                  os.rmdir(dir_path)
                  print("folder is deleted")
              except:
                  print("folder is not there")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多