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

问题描述 投票:0回答:5

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

但是,它会多次运行

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")
,它会运行多次。

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

python file-exists
5个回答
49
投票

您可以使用

else
for
块:

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.

每当循环内的

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


此外,您可以使用

glob

 模块代替 
listdir:

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



22
投票
any


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



8
投票

glob

 模块来准确查找您感兴趣的文件:
import glob fileList = glob.glob("*.true") for trueFile in fileList: doSomethingWithFile(trueFile)



3
投票
Path

来做类似的事情: from pathlib import Path cwd = Path.cwd() for path in cwd.glob("*.true"): print("true") DoSomething(path)



0
投票

`导入操作系统

对于 os.listdir(".") 中的文件:

if File.endswith(".true"): print("true") 否则:标志=true

if 标志:-你的代码- `

© www.soinside.com 2019 - 2024. All rights reserved.