rcubefather rcubefather - 6 months ago 21
Python Question

How to pick each line from 3 files in parllel and print in single line using Python?

I have 3 files and want to print lines that are a combination of the same line from each file. The files can have any number of lines. How can I iterate over three files in parallel?







Expected output:

Protocol 'http' for website 'facebook' with port '23'
Protocol 'ftp' for website 'yahoo' with port '45'
Protocol 'sftp' for website 'gmail' with port '56'

from time import sleep
with open ("C:/Users/Desktop/3 files read/protocol.txt", 'r') as test:
for line in test:
with open ("C:/Users/Desktop/3 files read/website.txt", 'r') as test1:
for line1 in test1:
with open ("C:/Users/Desktop/3 files read/port.txt", 'r') as test2:
for line2 in test2:
print "Protocol (%s) for website (%s) with port (%d)" % line, line1, line2


Here is my version:

import os.path
directory = "C:/Users/balu/Desktop/3 files read"
with open(os.path.join(directory, "protocol.txt"), 'r') as f1,\
     open(os.path.join(directory, "website.txt"), 'r') as f2,\
     open(os.path.join(directory, "port.txt"), 'r') as f3:

     for l1, l2, l3 in zip(f1, f2, f3):
         print "Protocol %s for website %s with port %d" % (l1.rstrip(), l2.rstrip(), int(l3))

I used the directory variable to simplify the code. Notice that I joined the elements using os.path.join(), which is safer than just putting a directory separator there.

Using zip(), we iterate through the three file objects. Using zip() means that the loop will exit on the file with the fewer lines, if they are uneven. If you cannot guarantee that they all have the same number of lines, then you might need to put an extra check in there.

By the way, at least some of this information is in the etc/services file.