Search code examples
pythonreadlines

Read lines from Multiple files


I have two files:

A:

John
Kevin
Richard

B:

Manager
Salesperson
Doctor

I am trying to read lines from both the files simultaneously and print the following:

Output:

John is a Manager
Kevin is a Salesperson
Richard is a Doctor

I tried using contextlib.izip package but it's not working.

Code:

with open('name') as names:
        with open('job') as jobs:
                for names1 in names:
                        jobs1 = jobs.readlines()
                        print names1 + jobs1

But this throws error as

`TypeError: cannot concatenate 'str' and 'list' objects`

I also tried using contextlib package but it didn't work.


Solution

  • You can do that with the zip function, and multiple context managers:

    with open('name') as name_file, open('job') as job_file:
    
        for name_line, job_line in zip(name_file, job_file):
    
            print("{} is a {}".format(
                name_line.strip(), job_line)) # don't forget to strip the newline 
                                              # from the names
    

    This code will work for Python 3. If you are working in Python 2, use itertools.izip().

    The other solutions posted here that utilize readlines() work, but they use an unnecessary amount of memory. There is no need to read in two whole files when all you care about is a single pair of lines at a time, so I would strongly recommend the iterator approach I have described here instead.