2

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?

4 Answers 4

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Specifically, doing: buf = g.readlines() and then replacing for row in g with for row in buf will probably do what you expect, as long as it's comfortable to hold DataTable in memory. (Also, if you have a big data set you can hold in memory you will query repeatedly, it is probably faster to read DataTable into a dictionary and query the dictionary rather than to do a search through a DataTable list every time you want to access a value.)
0

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.

Comments

0

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.