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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:17:40  来源:igfitidea点击:

Check if a directory contains a file with a given extension

pythonfile-exists

提问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 elsemultiple times because there are multiple files with alternate extensions. It must only run the elseif 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 elseblock of the for:

您可以使用以下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.

The elseattached to a forwill be run whenever the breakinside the loop is notexecuted. If you think a forloop as a way to search something, then breaktells whether you have found that something. The elseis 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 globmodule 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")

回答by bgporter

You should use the globmodule to look for exactly the files that you're interested in:

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

import glob

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