Python 文件列表
Python file listing
我正在尝试查找以 '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)
如何传递所有要存储的文件?
您的列表在每次迭代中都会被最新值覆盖。您必须使用内置的 .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
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)
我正在尝试查找以 '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)
如何传递所有要存储的文件?
您的列表在每次迭代中都会被最新值覆盖。您必须使用内置的 .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
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)