w3resource

Python File I/O: Combine each line from first file with the corresponding line in second file


14. Combine Lines from Two Files

Write a Python program to combine each line from first file with the corresponding line in second file.

Sample Solution:-

Python Code:

with open('abc.txt') as fh1, open('test.txt') as fh2:
    for line1, line2 in zip(fh1, fh2):
        # line1 from abc.txt, line2 from test.txtg
        print(line1+line2)
		

Sample Output:

Red                                                                                                           
Welcome to w3resource.com.                                                                                    
                                                                                                              
Green                                                                                                         
Append this text.Append this text.Append this text. 
------
Yellow                                                                                                        
Append this text.

Flowchart:

Flowchart: File I/O: Combine each line from first file with the corresponding line in second file.

For more Practice: Solve these Related Problems:

  • Write a Python program to combine each line from two files into a single line separated by a comma and then print the result.
  • Write a Python program to merge two files line by line by concatenating corresponding lines and then output the combined content.
  • Write a Python program to interleave the lines of two files and write the resulting lines to a new file.
  • Write a Python program to pair each line from the first file with the corresponding line from the second file and format the output as CSV.

Go to:


Previous: Write a Python program to copy the contents of a file to another file .
Next: Write a Python program to read a random line from a file.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.