[英]how can I find whether there is any txt file in a directory or not with Python
I would like to find that whether there is any file exists in a specific directory or not with using python. 我想找到使用python在特定目录中是否存在任何文件。
Something like this; 像这样的东西;
if os.path.exists('*.txt'):
# true --> do something
else:
# false --> do something
You can use glob.iglob
with next
: 你可以使用
next
glob.iglob
:
import glob
if next(glob.iglob('*.txt'), False):
#do something
else:
#do something else
Here if glog.iglob
returns an empty iterator then the default value False
will be used. 这里,如果
glog.iglob
返回一个空迭代器,那么将使用默认值False
。
or as @user2357112 suggested in comments, we can simply use any
as it returns False
for an empty iterable.: 或者作为@ user2357112在评论中建议,我们可以简单地使用
any
因为它为空迭代返回False
:
if any(glob.iglob('*.txt')):
#do something
else:
#do something else
You can use glob.glob
with wildcards and check whether it returns anything. 您可以将
glob.glob
与通配符一起使用,并检查它是否返回任何内容。 For instance: 例如:
import glob
if glob.glob('*.txt'):
# file(s) exist -> do something
else:
# no files found
Note that glob.glob
return a list of files matching the wildcard (or an empty list). 请注意,
glob.glob
返回与通配符(或空列表)匹配的文件列表。
os.listdir() will get you everything that's in a directory - files and directories os.listdir()将为您提供目录中的所有内容 - 文件和目录
import os
if not os.listdir(dir):
#do something
else:
#do something
For those getting here from google there is another solution you can use for checking if a glob is empty or not. 对于那些从谷歌到这里的人,你可以使用另一个解决方案来检查一个glob是否为空。
The previous answers are sufficient in themselves, however you can also determine the amount of files returned by a glob using len() , and use that as a comparison. 以前的答案本身就足够了,但是您也可以使用len()确定glob返回的文件数量,并将其用作比较。
if(len(glob.glob('*.txt')) == 0):
#Glob has no files
else:
#Continue
This will let you confirm if the glob does, or does not, have files. 这将让你确认glob是否有文件。 This also lets you confirm that the glob has more than or less than a specific quantity of files, should you need to do so.
如果需要,还可以确认glob具有多于或少于特定数量的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.