I have two multiline txt files.
File1 :
- one
- two
- three
File2 :
- uno
- dos
- tres
I would like to create a merged file that looks like this :
- one
- uno
- two
- dos
- three
- tres
So far I have only found one solution that can do this:
import itertools
with open('file1.txt', 'r') as f1, open('file2.txt', 'r') as f2:
# Merge data:
w1 = [line.strip() for line in f1]
w2 = [line.strip() for line in f2]
iters = [iter(w1), iter(w2)]
result = list(it.next() for it in itertools.cycle(iters))
# Save data:
result_file = open('result.txt', 'w')
for line in result:
result_file.write("{}\n".format(line))
result_file.close()
but I keep on getting the error message.
AttributeError: ‘list_iterator’ object has no attribute ‘next’
Can someone tell me what I did wrong, is there a better way to achieve this? Thanks in advance!
>Solution :
Files are iterators, so you can zip them:
with open('file1.txt') as f1, open('file2.txt') as f2, open('result.txt', 'w') as out:
for line1, line2 in zip(f1, f2):
out.write(line1)
out.write(' ')
out.write(line2)