我试图使用Python获取目录中的文件列表,但我不想要所有文件的列表。
我本质上想要的是做以下事情的能力,但使用Python而不执行ls。
ls 145592*.jpg
如果没有内置方法,我目前正在考虑编写一个for循环来遍历os.listdir()的结果,并将所有匹配的文件附加到一个新列表中。
但是,该目录中有很多文件,因此我希望有一个更有效的方法(或内置方法)。
我试图使用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, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']
https://docs.python.org/3/library/fnmatch.html
使用操作系统。遍历递归列出您的文件
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)
你可以使用subprocess. check_output()作为
import subprocess
list_files = subprocess.check_output("ls 145992*.jpg", shell=True)
当然,引号之间的字符串可以是您希望在shell中执行并存储输出的任何内容。
在“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]
您可以定义模式并检查它。在这里,我已经采取了开始和结束模式,并在文件名中寻找它们。FILES包含目录中所有文件的列表。
import os
PATTERN_START = "145592"
PATTERN_END = ".jpg"
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
for r,d,FILES in os.walk(CURRENT_DIR):
for FILE in FILES:
if PATTERN_START in FILE.startwith(PATTERN_START) and PATTERN_END in FILE.endswith(PATTERN_END):
print FILE