Python 检查目录是否包含具有给定扩展名的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33400682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a directory contains a file with a given extension
提问by spikespaz
I need to check the current directory and see if a file with an extension exists. My setup will (usually) only have one file with this extension. I need to check if that file exists, and if it does, run a command.
我需要检查当前目录并查看是否存在带有扩展名的文件。我的设置(通常)只有一个带有此扩展名的文件。我需要检查该文件是否存在,如果存在,则运行命令。
However, it runs the else
multiple times because there are multiple files with alternate extensions. It must only run the else
if the file does not exist, not once for every other file. My code sample is below.
但是,它运行了else
多次,因为有多个具有备用扩展名的文件。它必须仅else
在文件不存在时运行,而不是每隔一个文件运行一次。我的代码示例如下。
The directory is structured like so:
该目录的结构如下:
dir_________________________________________
\ \ \ \
file.false file.false file.true file.false
When I run:
当我运行时:
import os
for File in os.listdir("."):
if File.endswith(".true"):
print("true")
else:
print("false")
The output is:
输出是:
false
false
true
false
The issue with this is if I replaced print("false")
with something useful, it will run it multiple times.
问题是如果我print("false")
用一些有用的东西替换它,它会多次运行它。
Edit:I asked this question 2 years ago, and it's still seeing very mild activity, therefore, I'd like to leave this here for other people: http://book.pythontips.com/en/latest/for_-_else.html#else-clause
编辑:我 2 年前问过这个问题,它仍然看到非常温和的活动,因此,我想把这个留给其他人:http: //book.pythontips.com/en/latest/for_-_else。 html#else 子句
采纳答案by Bakuriu
You can use the else
block of the for
:
您可以使用以下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.
The else
attached to a for
will be run whenever the break
inside the loop is notexecuted. If you think a for
loop as a way to search something, then break
tells whether you have found that something. The else
is run when you didn't found what you were searching for.
在else
连接到for
无论何时将运行break
在内部循环不执行。如果您认为for
循环是搜索某物的一种方式,则break
说明您是否找到了该某物。在else
当你没有找到你正在寻找运行。
Alternatively:
或者:
if not any(fname.endswith('.true') for fname in os.listdir('.')):
# do stuff if a file .true doesn't exist
Moreover you could use the glob
module instead of listdir
:
此外,您可以使用glob
模块而不是listdir
:
import glob
# stuff
if not glob.glob('*.true')`:
# do stuff if no file ending in .true exists
回答by Kevin
If you only want to check that any file ends with a particular extension, use any
.
如果您只想检查任何文件是否以特定扩展名结尾,请使用any
.
import os
if any(File.endswith(".true") for File in os.listdir(".")):
print("true")
else:
print("false")