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

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

ls 145592*.jpg

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

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


当前回答

你可以使用subprocess. check_output()作为

import subprocess

list_files = subprocess.check_output("ls 145992*.jpg", shell=True) 

当然,引号之间的字符串可以是您希望在shell中执行并存储输出的任何内容。

其他回答

使用操作系统。遍历递归列出您的文件

import os
root = "/home"
pattern = "145992"
alist_filter = ['jpg','bmp','png','gif'] 
path=os.path.join(root,"mydir_to_scan")
for r,d,f in os.walk(path):
    for file in f:
        if file[-3:] in alist_filter and pattern in file:
            print os.path.join(root,file)

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

from pathlib import Path

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

你可以使用subprocess. check_output()作为

import subprocess

list_files = subprocess.check_output("ls 145992*.jpg", shell=True) 

当然,引号之间的字符串可以是您希望在shell中执行并存储输出的任何内容。

glob()绝对是实现它的方式(根据Ignacio)。然而,如果你确实需要更复杂的匹配,你可以用一个列表理解和re.match()来做,就像这样:

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]

更灵活了,但正如你所说,效率降低了。

import glob

jpgFilenamesList = glob.glob('145592*.jpg')

参见python文档中的glob