0

What I am trying to do is read a line from one file to a string, then search another file for the line that contains that string and parse that line with .split().

My code looks like this:

for line in portslist:
    marker = line.split()
    printername = marker[0]
    address = marker[1]

    for lines in constantfile:
        if address in line: #if the desired address is in the line
            lineholder = line
            lineholder = lineholder.split()
            oldonline = lineholder[4]
            oldutc = lineholder[5]
            status = lineholder[2]

However, I get the error

in readermain oldonline=lineholder[4] IndexError: list index out of range

After some trouble shooting it appears that the line from my constantfile is never being assigned to line. Instead it seems the line from the file portlist is being assigned to line, which only has an index of two.

My question is how to make the line that the string "address" is in assigned to line so I can parse and use it?

4

2 回答 2

3

I think you are using line where you should be using lines:

for lines in constantfile:
    if address in lines: #if the desired address is in the line
        lineholder=lines.split()
        # etc.

Also, if constantfile is a file object, that iterator will be exhausted after the first pass of the outer for loop.

于 2012-08-30T21:08:09.970 回答
0

Your indentation makes it so that even if "address in line" evaluates false, the rest of the block will run.

Second, the line from constantfile should assign to variable "lines". Reword the corresponding code to

if address in lines:
    lineholder = lines
    ...

and you should be good.

Furthermore, I would suggest a less arbitrary naming convention that makes it explicit that you are dealing with lines from 2 different files. For example

  • line -> portline
  • marker -> portlinesplit
  • lines -> constline
  • lineholder -> constlinesplit

That way it would be less confusing, and your code would be more readable.

于 2012-08-30T21:13:29.183 回答