簡體   English   中英

在python中的一行中連接大量文件

[英]Concatenate a large number of files line for line in python

謝謝你在這里借你的眼睛。

我正在處理幾百個文本文件(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

我認為您可以從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)

這是一種使用生成器的有趣方法:

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 粘貼命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM