首页 > 解决方案 > 如何将目录中文件数量的内容添加到相同数量的列表中

问题描述

我有很多带有名称列表的 .txt 文件(每行 - 一个名称),我想将每个文件内容附加到一个列表中。我希望将这些列表作为一个大列表中的子列表。我需要将每个文件的内容作为 final_product 列表中的单独子列表。

1.txt 的内容可以是:NAME1 NAME2 NAME3 ... 2.txt 的内容可以是:NAME4 NAME5 NAME6 ... 。. . N.txt 的内容可能是:NAMEn NAMEo NAMEp

输出应该是 [[NAME1,NAME2,NAME3],[NAME4,NAME5,NAME6],...[NAMEn,NAMEo,NAMEp]]

我能够编写代码,每个文件写入命令的位置在哪里,但我需要为所有文件编写一个循环。

 name1 = []
 name2 = []
 .
 .
 .
 nameN = []

 a = open(r'U:/1.txt','r')
 for line in a:
     name1.append(line.strip())

 b = open(r'U:/2.txt','r')
 for line in b:
     name2.append(line.strip())
 .
 .
 .
 N = open(r'U:/N.txt','r')
 for line in N:
     nameN.append(line.strip())

 final_product = [name1,name2,...,nameN]

编辑:

我试图用这个新代码解决这个问题:

import os
list_of_files = []
product = []
final_product = []

working_dir = r"U:/Work/"
os.chdir(working_dir)

def create_sublists(fname):
    with open(fname, 'r', encoding = 'ansi') as f:
        for line in f:
            product.append(line.strip()) #append each line from file to product
    final_product.append(product) #append the product list to final_product
    product.clear() #clear the product list
    f.close()

#create list of all files in the working directory
for file in os.listdir(working_dir):
    if file.endswith('.txt'):
        list_of_files.append(file)

for file in list_of_files:
    create_sublists(file)

print(final_product)

我认为它会以这种方式工作:第一个文件将其内容写入列表产品,此列表将附加到列表 final_product,列表产品将被清除,然后将附加第二个文件....但现实是该函数在最终产品中创建与文件夹中的文件一样多的空子列表,例如文件夹中的 6 个文件:[[]、[]、[]、[]、[]、[]] 你能请尝试帮助我?

标签: python

解决方案


如果我正确理解了你的问题

import os

loc = r'path/to/your/directory/'   # if you are on windows use the r
files = os.listdir(path)  # list of all files in the directory

final_product = []
for file in files:   #Loop over the files and add the lines
     a = open(loc+file,'r')
     for line in a:
         final_product.append([line.strip()])
     a.close()



推荐阅读