我想检查一下目录中是否有.rar
文件。它不需要是递归的。
在os.path.isfile()
中使用通配符是我最好的猜测,但它不起作用。那我能做什么呢?
发布于 2010-11-28 17:17:26
glob就是您所需要的。
>>> import glob
>>> glob.glob('*.rar') # all rar files within the directory, in this case the current working one
如果路径是现有的常规文件,则os.path.isfile()
返回True
。因此,它用于检查文件是否已经存在并且不支持通配符。glob
就是这样。
发布于 2010-11-29 01:12:37
如果不使用os.path.isfile()
,您将不知道glob()
返回的结果是文件还是子目录,因此尝试如下所示:
import fnmatch
import os
def find_files(base, pattern):
'''Return list of files matching pattern in base folder.'''
return [n for n in fnmatch.filter(os.listdir(base), pattern) if
os.path.isfile(os.path.join(base, n))]
rar_files = find_files('somedir', '*.rar')
如果愿意,您还可以只过滤glob()
返回的结果,这样做的好处是可以做一些与unicode相关的额外工作。如果重要的话,请检查glob.py中的源代码。
[n for n in glob(pattern) if os.path.isfile(n)]
发布于 2010-11-28 17:23:11
import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and x[-4:] == ".rar"]
https://stackoverflow.com/questions/4296138
复制相似问题