Reading Time: 1 minutes
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
# contents of textOne.txt Agilent Technologies Alcoa Corporation Aac Holdings Inc Aaron's Inc Advance Auto Parts Inc # contents of textTwo.txt A AA AAC AAN AAP ## EXPECTED OUTPUT ## Agilent Technologies : A Alcoa Corporation : AA Aac Holdings Inc : AAC Aaron's Inc : AAN 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) fhOne.close() fhTwo.close()
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.
Try it here.