我试图使用Python获取目录中的文件列表,但我不想要所有文件的列表。

我本质上想要的是做以下事情的能力,但使用Python而不执行ls。

ls 145592*.jpg

如果没有内置方法,我目前正在考虑编写一个for循环来遍历os.listdir()的结果,并将所有匹配的文件附加到一个新列表中。

但是,该目录中有很多文件,因此我希望有一个更有效的方法(或内置方法)。


当前回答

在“path/to/images”中扩展名为“jpg”和“png”的文件名:

import os
accepted_extensions = ["jpg", "png"]
filenames = [fn for fn in os.listdir("path/to/images") if fn.split(".")[-1] in accepted_extensions]

其他回答

你可能也喜欢更高级的方法(我已经实现并打包为findtools):

from findtools.find_files import (find_files, Match)


# Recursively find all *.txt files in **/home/**
txt_files_pattern = Match(filetype='f', name='*.txt')
found_files = find_files(path='/home', match=txt_files_pattern)

for found_file in found_files:
    print found_file

可与

pip install findtools

在“path/to/images”中扩展名为“jpg”和“png”的文件名:

import os
accepted_extensions = ["jpg", "png"]
filenames = [fn for fn in os.listdir("path/to/images") if fn.split(".")[-1] in accepted_extensions]

您可以使用Python标准库3.4及以上版本中提供的pathlib。

from pathlib import Path

files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]

另一个选择:

>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']

https://docs.python.org/3/library/fnmatch.html

您可以使用列表推导式和其中的正则表达式检查器来简化它,包括带有指定后缀的图像文件。

import re
import os

dir_name = "."
files = [os.path.join(dir_name, f) for f in os.listdir(dir_name) if re.match(r'.*\.(jpg|jpeg|png)', f)]