【问题标题】:Check if a directory contains a file with a given extension检查目录是否包含具有给定扩展名的文件
【发布时间】:2016-01-28 19:04:46
【问题描述】:

我需要检查当前目录并查看是否存在带有扩展名的文件。我的设置(通常)只有一个带有此扩展名的文件。我需要检查该文件是否存在,如果存在,请运行命令。

但是,它会多次运行else,因为有多个文件具有备用扩展名。如果文件不存在,它必须只运行else,而不是每隔一个文件运行一次。我的代码示例如下。


目录结构如下:

dir_________________________________________
    \            \            \            \     
 file.false    file.false    file.true    file.false

当我跑步时:

import os
for File in os.listdir("."):
    if File.endswith(".true"):
        print("true")
    else:
        print("false")

输出是:

false
false
true
false

问题在于,如果我将 print("false") 替换为有用的东西,它会运行多次。

编辑:我在 2 年前问过这个问题,它仍然看到非常轻微的活动,因此,我想把这个留给其他人:http://book.pythontips.com/en/latest/for_-_else.html#else-clause

【问题讨论】:

    标签: python file-exists


    【解决方案1】:

    类似于@bgporter 的解决方案,您也可以使用 Path 来做类似的事情:

    import Path
    cwd = Path.cwd()
    for path in cwd.glob("*.true"):
       print("true")
       DoSomething(path)
    

    【讨论】:

      【解决方案2】:

      您可以使用forelse 块:

      for fname in os.listdir('.'):
          if fname.endswith('.true'):
              # do stuff on the file
              break
      else:
          # do stuff if a file .true doesn't exist.
      

      只要循环内的break执行,附加到forelse 就会运行。如果您认为for 循环是一种搜索某些内容的方法,那么break 会告诉您是否找到了该内容。 else 在您没有找到您要搜索的内容时运行。

      或者:

      if not any(fname.endswith('.true') for fname in os.listdir('.')):
          # do stuff if a file .true doesn't exist
      

      此外,您可以使用glob 模块代替listdir

      import glob
      # stuff
      if not glob.glob('*.true')`:
          # do stuff if no file ending in .true exists
      

      【讨论】:

      • 使用新的 pathlib 库,您可以将 glob 更改为 if not list(pathlib.Path(".").rglob("*.true"))
      【解决方案3】:

      您应该使用glob 模块准确查找您感兴趣的文件:

      import glob
      
      fileList = glob.glob("*.true")
      for trueFile in fileList:
          doSomethingWithFile(trueFile)
      

      【讨论】:

        【解决方案4】:

        如果您只想检查任何文件是否以特定扩展名结尾,请使用any

        import os
        if any(File.endswith(".true") for File in os.listdir(".")):
            print("true")
        else:
            print("false")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-14
          • 2012-04-02
          • 2011-08-22
          • 2019-08-24
          • 2017-10-29
          • 2011-05-04
          相关资源
          最近更新 更多