Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert one multiline txt file into another line by line

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading