2

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.

user3198755
  • 477
  • 2
  • 10
  • 21
  • possible duplicate of [Read two textfile line by line simultaneously -python](http://stackoverflow.com/questions/11295171/read-two-textfile-line-by-line-simultaneously-python) – skrrgwasme Feb 12 '15 at 18:46

3 Answers3

4

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.

skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
0

You basically want this:

# These can come from open("file").readlines()
a = ("John", "Kevin", "Richard")
b = ("Manager", "Salesperson", "Doctor")

for person, role in zip(a, b):
    print("{} is a {}".format(person, role))
Mark R.
  • 1,273
  • 8
  • 14
0

You can read the two files separately and then zip the results

i.e.

with open('name') as f:
    name = f.readlines()

with open('job') as f:
    job = f.readlines()

roles = zip(name, job)

Or, you can use a nested loop as you show in your code. the problem is in readlines(), which will return all lines read. However, a file object is a generator in python, so you can iterate over it simply.

with open('name') as names:
    with open('job') as jobs:
        for n in names:
            for j in jobs:
                print("{n} is a {j}".format(n=n, j=j))

I prefer the first option because its more readable.

Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85