首页 > 解决方案 > 如何在单个列表中合并列表值?

问题描述

我在一个文件夹中有很多文件。我想选择最新的文件。我也编写了代码,但它在单独的列表中给出了值。

我得到的输出:

['tb_exec_ns_decile_20190129']
['tb_exec_ns_decile_20190229']
['tb_exec_ns_decile_20190329']

预期输出:

['tb_exec_ns_decile_20190129', 'tb_exec_ns_decile_20190229', 'tb_exec_ns_decile_20190329']

代码:

path1 = "D:/Users/SPate233/Downloads/testing/*.csv"
files = glob.glob(path1)
print(files)

for name in files:
    new_files = []
    new_files = os.path.split(name)[1].split('.')[0]
    new_files = new_files.split(',')
    print(new_files)

标签: python

解决方案


这里的正确术语append不是merge,因为您希望将列表中的所有文件名放在一起,创建一个空列表以将所有文件名存储在其中:

f_list = []                              # an empty list to store the file names
for name in files:
    file_name = os.path.split(name)[1].split('.')[0]
    f_list.append(file_name.split(','))  # appending the names to the list

print(f_list)                            # print the list

推荐阅读