【问题标题】:How to check to see if a folder contains files using python 3如何使用python 3检查文件夹是否包含文件
【发布时间】:2014-10-29 18:51:43
【问题描述】:

我到处寻找这个答案,但找不到。

我正在尝试编写一个脚本来搜索特定的子文件夹,然后检查它是否包含任何文件,如果是,则写出该文件夹的路径。我已经弄清楚了子文件夹搜索部分,但是检查文件让我很困惑。

我发现了多个关于如何检查文件夹是否为空的建议,并且我尝试修改脚本以检查文件夹是否为空,但我没有得到正确的结果。

这是最接近的脚本:

for dirpath, dirnames, files in os.walk('.'):
if os.listdir(dirpath)==[]:
    print(dirpath)

这将列出所有空的子文件夹,但如果我尝试将其更改为:

if os.listdir(dirpath)!=[]:
    print(dirpath)

它将列出所有内容——不仅仅是那些包含文件的子文件夹。

如果有人能指出我正确的方向,我将不胜感激。

这适用于 Python 3.4,如果这很重要的话。

感谢您能给我的任何帮助。

【问题讨论】:

  • “空”是指“不包含任何内容(... 除外)”,还是“除了子目录不包含任何内容”,还是“不包含任何内容”任何常规文件”,或“不包含任何非隐藏的常规文件”,或不同的东西?
  • 同时,你为什么使用os.walk,然后在每个dirpath上也使用os.listdir?您已经拥有dirnamesfiles;为什么要调用一个函数来获取你已经拥有的相同信息?
  • 最后,你几乎不想检查!= []== []。只需使用空序列是错误的,而非空序列是真实的这一事实:if not os.listdir(dirpath): 会做你想做的事。
  • 空,我的意思是没有常规文件。我的问题是我无法按扩展名搜索,因为正在使用许多不同的文件类型(.txt、.csv、.xls 等),我不知道所有类型的文件都存储在这些子目录中,并且我不想错过任何常规文件。
  • 我不确定您是否知道“常规文件”的含义。它与扩展无关;常规文件是不是目录、块设备、FIFO 等的文件。您可以通过stat(或仅通过调用os.path.isfile)来判断。如果这确实是您想要的,仅使用 walk 中的 files 是不够的 - 排除目录,但不排除其他任何内容。

标签: python python-3.4


【解决方案1】:

'files' 已经告诉你目录中有什么。只需检查一下:

for dirpath, dirnames, files in os.walk('.'):
    if files:
        print(dirpath, 'has files')
    if not files:
        print(dirpath, 'does not have files')

【讨论】:

  • 我希望它只打印那些有文件的路径。我想忽略那些没有文件的路径。如果这可以调整为只打印那些有文件的路径,那么这正是我所需要的。
  • Duh——我只是想从代码中删除“如果不是”行,并得到了我需要的东西。非常感谢大家从这个新手到 Python 的所有帮助。 :)
  • LOL - 它同时显示是因为您的代码中有 ==!= 示例。我本来可以更清楚的。
  • 对于那些挣扎的人:dir=r'C:\Users\x\Desktop\folder name' 然后for dirpath, dirnames, files in os.walk(dir): 和其余代码
  • 如果有数百个文件,os.walk(".") 不会占用内存吗? @tdelaney
【解决方案2】:

添加到@Jon Clements 的 pathlib 答案,我想用 pathlib 检查文件夹是否为空但不创建集合:

from pathlib import Path

# shorter version from @vogdb
is_empty = not any(Path('some/path/here').iterdir())

# similar but unnecessary complex
is_empty = not bool(sorted(Path('some/path/here').rglob('*')))

vogdb 方法尝试遍历给定目录中的所有文件。如果没有文件,any() 将为 False。我们用 not 来否定它,如果没有文件,is_empty 为 True,如果有文件,则为 False。

sorted(Path(path_here).rglob('*')) 返回已排序的 PosixPah 项目列表。如果没有项目,则返回一个空列表,即 False。因此,如果路径为空,is_empty 将为 True,如果路径有内容,则为 false

类似的想法结果 {} 和 [] 给出相同的结果:

【讨论】:

  • 这个想法一样any(Path(''some/path/here'').iterdir())
  • 不错的解决方案。两点说明:可以使用list() 而不是sorted() 进行更有效的计算,因为顺序无关紧要。 len(list(Path(p).rglob('*'))) == 0 而不是 bool 更具可读性恕我直言(或检查 next 并捕获异常)。
【解决方案3】:

您可以利用 Python 3.4 中引入的新 pathlib 库递归提取所有非空子目录,例如:

import pathlib

root = pathlib.Path('some/path/here')
non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}

由于您无论如何都必须遍历树,因此我们构建了一组父目录,其中存在一个文件,这会产生一组包含文件的目录 - 然后按照您的意愿处理结果。

【讨论】:

    【解决方案4】:

    如果可以删除目录,可以这样:

    my_path = os.path.abspath("something")               
    try:
        os.rmdir(my_path)
        is_empty = True
        # Do you need to keep the directory? Recreate it!
        # os.makedirs(my_path, exist_ok=True)
    except OSError:
        is_empty = False
    
    if is_empty:
        pass
    

    os.rmdir 仅在目录为空时删除目录,否则抛出 OSError 异常。

    您可以在以下位置找到关于此的讨论:

    1. https://bytes.com/topic/python/answers/157394-how-determine-if-folder-empty

    例如,当你打算做一个 git clone 时,删除一个空目录是可以的,但如果你事先检查目录是否为空,那么你的程序就不会抛出空目录错误。

    【讨论】:

    • 我们是否应该在删除后重新创建文件夹:os.makedirs(submodule_absolute_path) after is_empty = True
    • 这取决于您的应用程序/工作。如果目录为空时不需要该目录,则不需要。但是如果你需要保留它,即使它是空的,那么,是的。我更新了问题。
    【解决方案5】:
    entities = os.listdir(dirpath)
    for entity in entities:
        if os.path.isfile(entity):
            print(dirpath)
            break
    

    【讨论】:

      【解决方案6】:

      检查文件夹是否包含文件:

      import os
      import shutil
      
      if len(os.listdir(folder_path)) == 0: # Check is empty..
          shutil.rmtree(folder_path) # Delete..
      

      【讨论】:

        【解决方案7】:

        使用pathlib,可以按如下方式完成:

        import pathlib
        
        # helper function
        def is_empty(_dir: pathlib.Path) -> bool:
            # return not bool([_ for _ in _dir.iterdir()])
            return not any(_dir.iterdir())
        
        # create empty dir
        _dir = pathlib.Path("abc")
        
        # check if dir empty
        is_empty(_dir)  # will return True
        
        # add files to folder and call it again
        
        
        

        【讨论】:

        • 使用not 意味着你不需要bool[_ for _ in ...] 最好写成list(...)。整个表达式简化为not any(_dir.iterdir())
        【解决方案8】:

        你可以使用这个简单的代码:

        dir_contents = [x for x in os.listdir('.') if not x.startswith('.')]
        if len(dir_contents) > 0:
            print("Directory contains files")
        

        它检查当前工作目录 (.) 中的文件和目录。您可以更改os.listdir() 中的. 以检查任何其他目录。

        【讨论】:

          【解决方案9】:

          您可以直接使用生成器,而不是先转换为集合或(有序)列表:

          from pathlib import Path
          
          p = Path('abc')
          
          def check_dir(p):
          
              if not p.exists():
                  print('This directory is non-existent')
                  return
          
              try:
                  next(p.rglob('*'))
              except StopIteration:
                  print('This directory is empty')
                  return
          
              print('OK')
          

          【讨论】:

            【解决方案10】:

            现在可以在Python3.5+ 中更有效地完成此操作,因为无需构建目录内容列表来查看其是否为空:

            import os
            
            def is_dir_empty(path):
                with os.scandir(path) as scan:
                    return next(scan, None) is None
            

            【讨论】:

              【解决方案11】:

              我有关注Bash checking if folder has contents回答。

              os.walk('.') 返回一个目录下的完整文件,如果有数千个文件可能效率低下。而是遵循命令 find "$target" -mindepth 1 -print -quit 返回第一个找到的文件并退出。如果返回一个空字符串,则表示文件夹为空。

              您可以使用find 检查目录是否为空,并处理其 输出

              def is_dir_empty(absolute_path):
                  cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
                  output = subprocess.check_output(cmd).decode("utf-8").strip()
                  return not output
              
              print is_dir_empty("some/path/here")
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-06-17
                • 1970-01-01
                • 1970-01-01
                • 2014-05-10
                • 1970-01-01
                • 2015-09-14
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多