在python中连接大量的文件行

时间:2013-05-16 03:06:43

标签: python file-io concatenation

感谢您放眼睛。

我正在处理几百个文本文件形式的光谱数据(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()

我在上面的想法是,我需要将光标放回文档的开头,为每个文件..但它真的在我脸上爆炸。

非常感谢。

-matt

2 个答案:

答案 0 :(得分:1)

我认为你可以从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)

答案 1 :(得分:0)

这是使用生成器进行此操作的一种有趣方式:

import sys

files     = sys.argv[1:]
handles   = (open(f) for f in files)
readers   = ((line.strip() for line in h) for h in handles)
splitters = ((line.split(',')[1] for line in r) for r in readers)
joiners   = (",".join(tuple(s)) for s in splitters)

for j in joiners:
    print j

您也可以查看Unix paste命令

相关问题