Skip to main content
 首页 » 编程设计

python之在python中逐行连接大量文件

2025年05月04日9lidabo

感谢您的关注。

我正在处理一些以数百个文本文件(1.txt、2.txt、3.txt ...)形式存在的光谱数据,它们都采用完全相同的行数格式,如下所示: 为清楚起见:

1.txt:             2.txt:            3.txt: 
1,5                1,4               1,7 
2,8                2,9               2,14 
3,10               3,2               3,5 
4,13               4,17              4,9 
<...>              <...>             <...> 
4096,1             4096,7            4096,18 

我试图将它们逐行连接起来,这样我就可以得到一个输出文件,例如:

5,4,7 
8,9,14 
10,2,5 
13,17,9 
<...> 
1,7,18 

我是 Python 的新手,非常感谢这里的一些帮助。我试过这个烂摊子:

howmanyfiles=8 
output=open('output.txt','w+') 
for j in range(howmanyfiles): 
    fp=open(str(j+1) + '.txt','r') 
    if j==0: 
        for i, line in enumerate(fp): 
            splitline=line.split(",") 
            output.write(splitline[1]) 
    else: 
        output.close() 
        output=open('output.txt','r+') 
        for i, line in enumerate(fp): 
            splitline=line.split(",") 
            output.write(output.readline(i)[:-1]+","+splitline[1]) 
    fp.close() 
output.close() 

我在上面的想法是,我需要将光标放回每个文件的文档开头。但这真的让我大吃一惊。

非常感谢。

-哑光

请您参考如下方法:

我认为您可以从 zip 内置函数中获得很多好处,它可以让您同时遍历所有输入文件:

from contextlib import ExitStack 
 
num_files = 8 
with open("output.txt", "w") as output, ExitStack() as stack: 
    files = [stack.enter_context(open("{}.txt".format(i+1))) 
             for i in range(num_files)] 
    for lines in zip(*files): # lines is a tuple with one line from each file 
        new_line = ",".join(line.partition(',')[2] for line in lines) + "\n" 
        file.write(new_line)