【问题标题】:Python - how do delete content in a complicated folder without changing its structure?Python - 如何在不改变其结构的情况下删除复杂文件夹中的内容?
【发布时间】:2012-02-29 09:13:36
【问题描述】:

我有一个带有子文件夹的文件夹,每个文件夹可以包含更多的子文件夹等等。我想删除所有文件中的所有文件,但保持目录结构相同。是否有内置命令或者我必须为此使用 os.listdir 编写一些递归函数?

【问题讨论】:

    标签: python directory directory-structure


    【解决方案1】:

    os.walk:

    import os
    top = '/some/dir'
    for root, dirs, files in os.walk(top):
        for name in files:
            os.remove(os.path.join(root, name))
    

    【讨论】:

      【解决方案2】:

      无耻地从Files and Directories 上的 Python 文档中窃取,并省略了目录的删除:

      # Delete everything reachable from the directory named in "top",
      # assuming there are no symbolic links.
      # CAUTION:  This is dangerous!  For example, if top == '/', it
      # could delete all your disk files.
      import os
      for root, dirs, files in os.walk(top, topdown=False):
          for name in files:
              os.remove(os.path.join(root, name))
      

      【讨论】:

      • 谢谢。我只是在我的问题中添加了一些内容:我想确保保留系统/隐藏文件。我必须对您的代码进行哪些更改?谢谢-
      • 那么您必须对os.path.join(root, name) 执行检查以确保它不符合您的保存标准,可能使用stat 或使用string 比较。这完全取决于您的编码!
      • 好的如何检查文件是否为系统/隐藏文件?
      【解决方案3】:
      import os
      
      #check if file is hidden 
      def is_hidden(filepath):
          name = os.path.basename(os.path.abspath(filepath))
          return name.startswith('.')
      
      top = '/dir'
      for root, dirs, files in os.walk(top):
          for name in files:
             #do not delete hidden files (as asked by OP in comments)
             if is_hidden(name) == false:  
                os.remove(os.path.join(root, name))
      

      【讨论】:

      • 最好,除了一堵代码墙之外,您还应该提供一些解释或链接或一些东西
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多