Matthew Hill
Matthew Hill

Reputation: 35

Looping issues in Python

I'm trying to get information from a data table .txt file from a list of objects in another .txt file.
in the code List.txt looks like

Obj2
Obj5
Obj6
etc.

and DataTable.txt looks something like

Obj1    Data1
Obj2    Data2
Obj3    Data3
etc.

I tried

f = file('List.txt')
g = file('DataTable.txt')

for line in f:
    l = line.split()
    name = l[0]
    for row in g:
        if row.startswith(name):
            data = row.split()
            print data[8]

but it only prints the data for the first entry on the list. Can anyone find the problem?

Upvotes: 2

Views: 106

Answers (4)

Patrick Perini
Patrick Perini

Reputation: 22633

As you iterate over a file, you move the position that you're reading from. Think of it as a cursor moving through the file. In order to bypass this issue, simply read in the data before-hand and iterate over that.

f = file('List.txt').read().splitlines()       #read in the whole file, then split on the lines
g = file('DataTable.txt').read().splitlines()  #read in the whole file, then split on the lines

for line in f:
    l = line.split()
    name = l[0]
    for row in g:
        if row.startswith(name):
            data = row.split()
            print data[8]

Upvotes: 0

mattbornski
mattbornski

Reputation: 12543

To summarize the fine answers given by @Borealid and @Ignacio,

f = file('List.txt')
g = file('DataTable.txt')

for line in f:
    l = line.split()
    name = l[0]
    g.seek(0)
    for row in g:
        if row.startswith(name):
            data = row.split()
            print data[8]

Upvotes: 1

Borealid
Borealid

Reputation: 98469

The problem is that you went all the way through g on the first line of f. On the second line of f, g has nothing more to give.

You need to reset g back to its first line. You can do this by putting start_pos = g.tell() just after g.open, then a g.seek(start_pos) after the for row in g has completed.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Iterating over a file consumes it. Either seek back to the beginning, or cache one of the files in a sequence.

Upvotes: 0

Related Questions