我试图使用Python获取目录中的文件列表,但我不想要所有文件的列表。
我本质上想要的是做以下事情的能力,但使用Python而不执行ls。
ls 145592*.jpg
如果没有内置方法,我目前正在考虑编写一个for循环来遍历os.listdir()的结果,并将所有匹配的文件附加到一个新列表中。
但是,该目录中有很多文件,因此我希望有一个更有效的方法(或内置方法)。
我试图使用Python获取目录中的文件列表,但我不想要所有文件的列表。
我本质上想要的是做以下事情的能力,但使用Python而不执行ls。
ls 145592*.jpg
如果没有内置方法,我目前正在考虑编写一个for循环来遍历os.listdir()的结果,并将所有匹配的文件附加到一个新列表中。
但是,该目录中有很多文件,因此我希望有一个更有效的方法(或内置方法)。
当前回答
初步的代码
import glob
import fnmatch
import pathlib
import os
pattern = '*.py'
path = '.'
解决方案1 -使用“glob”
# lookup in current dir
glob.glob(pattern)
In [2]: glob.glob(pattern)
Out[2]: ['wsgi.py', 'manage.py', 'tasks.py']
解决方案 2 - 使用“os” + “fnmatch”
变体2.1 -查找当前目录
# lookup in current dir
fnmatch.filter(os.listdir(path), pattern)
In [3]: fnmatch.filter(os.listdir(path), pattern)
Out[3]: ['wsgi.py', 'manage.py', 'tasks.py']
变体2.2 -查找递归
# lookup recursive
for dirpath, dirnames, filenames in os.walk(path):
if not filenames:
continue
pythonic_files = fnmatch.filter(filenames, pattern)
if pythonic_files:
for file in pythonic_files:
print('{}/{}'.format(dirpath, file))
结果
./wsgi.py
./manage.py
./tasks.py
./temp/temp.py
./apps/diaries/urls.py
./apps/diaries/signals.py
./apps/diaries/actions.py
./apps/diaries/querysets.py
./apps/library/tests/test_forms.py
./apps/library/migrations/0001_initial.py
./apps/polls/views.py
./apps/polls/formsets.py
./apps/polls/reports.py
./apps/polls/admin.py
解决方案3 -使用“pathlib”
# lookup in current dir
path_ = pathlib.Path('.')
tuple(path_.glob(pattern))
# lookup recursive
tuple(path_.rglob(pattern))
注:
在Python 3.4上测试 模块“pathlib”只在Python 3.4中添加 Python 3.5使用glob.glob添加了递归查找的特性 https://docs.python.org/3.5/library/glob.html glob.glob。由于我的机器安装了Python 3.4,所以我还没有对此进行测试。
其他回答
import glob
jpgFilenamesList = glob.glob('145592*.jpg')
参见python文档中的glob
glob()绝对是实现它的方式(根据Ignacio)。然而,如果你确实需要更复杂的匹配,你可以用一个列表理解和re.match()来做,就像这样:
files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
更灵活了,但正如你所说,效率降低了。
您可以使用Python标准库3.4及以上版本中提供的pathlib。
from pathlib import Path
files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]
你可能也喜欢更高级的方法(我已经实现并打包为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
保持简单:
import os
relevant_path = "[path to folder]"
included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif']
file_names = [fn for fn in os.listdir(relevant_path)
if any(fn.endswith(ext) for ext in included_extensions)]
我更喜欢这种形式的列表推导式,因为它的英文可读性很好。
我把第四行读成: 对于os中的每一个fn。Listdir为我的路径,只给我匹配任何一个我所包含的扩展。
对于python程序员新手来说,可能很难真正习惯使用列表推导式进行过滤,而且对于非常大的数据集可能会有一些内存开销,但对于列出目录和其他简单的字符串过滤任务,列表推导式会带来更干净的可记录的代码。
关于这种设计的唯一问题是,它不能防止您犯传递字符串而不是列表的错误。例如,如果您意外地将一个字符串转换为一个列表,并最终检查字符串的所有字符,您可能最终会得到大量的假阳性结果。
但有一个容易解决的问题总比有一个难以理解的解决方案要好。