在os.path.isfile()中使用通配符

65 投票
8 回答
103034 浏览
提问于 2025-04-16 07:43

我想检查一个文件夹里有没有 .rar 文件。这个检查不需要递归,也就是说只看这个文件夹,不用去看里面的子文件夹。

我试着用通配符和 os.path.isfile() 来实现这个功能,但结果不太好。那我该怎么做呢?

8 个回答

10
import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

19

如果不使用 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)]
111

glob 是你需要的工具。

>>> import glob
>>> glob.glob('*.rar')   # all rar files within the directory, in this case the current working one

os.path.isfile() 这个函数会返回 True,如果你给它的路径是一个已经存在的普通文件。也就是说,它可以用来检查一个文件是否已经存在,但它不支持使用通配符。而 glob 是可以支持通配符的。

撰写回答