检查目录是否包含具有给定扩展名的文件

spi*_*paz 16 python file-exists

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

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


该目录的结构如下:

dir_________________________________________
    \            \            \            \     
 file.false    file.false    file.true    file.false
Run Code Online (Sandbox Code Playgroud)

当我跑:

import os
for File in os.listdir("."):
    if File.endswith(".true"):
        print("true")
    else:
        print("false")
Run Code Online (Sandbox Code Playgroud)

输出是:

false
false
true
false
Run Code Online (Sandbox Code Playgroud)

这个问题是,如果我print("false")用有用的东西替换它,它将运行多次.

编辑: 2年前我问过这个问题,而且它仍然看到非常温和的活动,因此,我想把这个留给其他人:http://book.pythontips.com/en/latest/for_-_else. HTML#else从句

Bak*_*riu 23

您可以使用以下elsefor:

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.
Run Code Online (Sandbox Code Playgroud)

else连接到for无论何时将运行break在内部循环执行.如果你认为for循环是一种搜索某种东西的方式,那就break告诉你是否找到了某种东西.在else当你没有找到你正在寻找运行.

或者:

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

此外,您可以使用该glob模块而不是listdir:

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

  • 使用新的 pathlib 库,您可以将 glob 更改为 `if not list(pathlib.Path(".").rglob("*.true"))` (2认同)

Kev*_*vin 10

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

import os
if any(File.endswith(".true") for File in os.listdir(".")):
    print("true")
else:
    print("false")
Run Code Online (Sandbox Code Playgroud)


bgp*_*ter 6

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

import glob

fileList = glob.glob("*.true")
for trueFile in fileList:
    doSomethingWithFile(trueFile)
Run Code Online (Sandbox Code Playgroud)