想象一下,我有两个文件,如:
'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.'
答案 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)
这将一次只加载一行(而不是所有文件)到内存。