簡體   English   中英

如何依次讀取兩個txt文件並將其寫入python中的新文件?

[英]how to sequentially read two txt files and write into a new file in python?

我有兩個txt文件,每個文件100000行,現在我需要生成一個新文件,該文件將前兩個txt文件中的內容組合在一起,使得第一個文件中的每32行和第二個文件中的每64行提取文件,然后將其寫入新文件,依此類推,直到兩個文件中的所有行都寫入新文件。

我將如何在python中做到這一點,我知道在一個文件中讀取所有行並將它們寫入另一個文件的方式。

with open(app_path+'/empty.txt','r') as source:
    data = [  (random.random(), line) for line in source ]
    data.sort()
with open(app_path+'/empty2.txt','w') as target:
    for _,line in data:
        target.write( line )

但是對於讀取2個文件,提取內容並順序寫入,我不知道

根據TessellatingHeckler,您將首先用盡文件2。 然后,此方法將繼續從其余文件寫入,直到完成。

from itertools import islice
with open('target.txt', 'w') as target:
    f1, f2 = open('f1.txt'), open('f2.txt')
    while True:
        ls1 = islice(f1, 32)
        if not ls1:
            # will not happen in this case
            target.write('\n' + f2.read())
            break
        ls2 = islice(f2, 64)
        if not ls2:
            target.write('\n' + f1.read())
            break
        target.write('\n'.join('\n'.join(ls) for ls in [ls1, ls2]))
    f1.close()
    f2.close()

暫無
暫無

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

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