【发布时间】:2020-04-14 07:41:29
【问题描述】:
我已尝试使用此代码查找文件夹中的所有“jpg”文件并从中列出。但结果显示如下。
['0', '0', '0', '1', '0', '8', '.', 'j', 'p', 'g']
['0', '0', '0', '1', '0', '8', '.', 'j', 'p', 'g', '0', '0', '0', '1', '1', '4', '.', 'j', 'p', 'g']
它返回文件名的所有字符而不是整个文件名。 你怎么解决这个问题?提前致谢。
import os
def find_names(outpath):
root_path_list= [file for file in os.listdir(outpath)]
jpg_file_list = []
for idx, file in enumerate(root_path_list) :
if file.endswith('.jpg'):
jpg_file_list += file
print(jpg_file_list)
【问题讨论】:
-
jpg_file_list += file确实扩展了列表,因此它添加了“文件”的所有元素(所有字母),使用jpg_file_list.append(file) -
顺便说一句,你的列表理解
[file for file in os.listdir(outpath)]什么都不做 - 你可以分配root_path_list = os.listdir(outpath)。