如何对齐两个大txt。文件逐行并返回第三个文件?

时间:2017-05-17 13:52:10

标签: python

想象一下,我有两个文件,如:

'My name is George.'
'I like music.'
'Today I'm going to the beach.'

在txt中。档案1。

'O meu nome é Jorge.' 
'Gosto de música.'
'Hoje vou à praia.'

在txt中。文件2

我需要在第三个文件中加入两个文件,如:

'My name is George.'

'O meu nome é Jorge.' 
'I like music.'
'Gosto de música.'
'Today I'm going to the beach.'
'Hoje vou à praia.'

2 个答案:

答案 0 :(得分:0)

您可以使用文件的readlines():

with open('english.txt', 'r') as input_file:
    english = input_file.readlines()

with open('spanish.txt', 'r') as input_file:
    spanish = input_file.readlines()

with open('combined.txt', 'w') as output_file:
    for i in range(len(english)):
        output_file.write(english[i])
        output_file.write(spanish[i])

答案 1 :(得分:0)

接受的答案有效,但只是建议一个更短且耗能更少的解决方案(你提到文件很大):

with open(filename1, "r") as f1, \ 
         open(filename2, "r") as f2, \
         open(filename3, "w") as f3:
    for l1,l2 in zip(f1,f2):
        f3.write(l1)
        f3.write(l2)

这将一次只加载一行(而不是所有文件)到内存。