Reading Time: 1 minutesPrinting corresponding lines of two files together in Python
Printing corresponding lines of two files together in Python
Printing corresponding lines of two files together: Write a Python script which prints corresponding lines of two files together.
printing corresponding lines of two files together
Advance Auto Parts Inc : AAP |
fhOne = open ( 'textOne.txt' ) |
fhTwo = open ( 'textTwo.txt' ) |
tuplesOfCorrespondingLines = zip (fhOne.read().splitlines(), fhTwo.read().splitlines()) |
for a, b in tuplesOfCorrespondingLines: |
print (a.rstrip(), ":" , b) |
The constructor of builtin class zip takes iterables as inputs amd returns an iterator of tuples of corresponding elements. The population of the iterator stops when the shortest input iterable is exhausted. For more information, check out this article.
The rstrip() function of class str strips trailing whitespace off the string. We have used it here to get rid of the \n character at the end of lines of textOne.txt.
See also: