Python文件清单

问题描述

我正在尝试查找文件夹中所有以'msCam'开头并以'.avi'扩展名结尾的文件。我设法用以下代码做到这一点:

path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         'msCam' in i]
print(len(files))
for file in files:
        if file.endswith(".avi"):
            msFileList = [os.path.join(path,file)]
            print(msFileList)

但这仅存储在给定的“ msFileList”变量中找到的最后一个文件

print(msFileList)

如何传递所有要存储的文件

View the output here

解决方法

path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
     'msCam' in i]
msFileList = [] #create and empty list
print(len(files))
for file in files:
    if file.endswith(".avi"):
        msFileList.appened(os.path.join(path,file)) #append result to list

print(msFileList)
,

这是您想要的吗?

filepath = './'
matching_files = []
with os.scandir(filepath) as entries:
    for entry in entries:
        if entry.name.startswith('msCam') and entry.name.endswith('.avi'):
            matching_files.append(entry.path+entry.name)
,

您的列表在每次迭代中都被最新值覆盖。您必须使用内置的.append()方法。

path = path_to_analyze
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         'msCam' in i]
print(len(files))

msFileList = [] # filenames will be appended in this list
for file in files:
        if file.endswith(".avi"):
            msFileList.append(os.path.join(path,file)) # using .append()
            # print(msFileList)

print(msFileList) # Whole List will be printed

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...