Home > database >  IndexError: list index out of range prints out only every second row in python
IndexError: list index out of range prints out only every second row in python

Time:03-22

I have a text file, that I would like to input line by line in python. My tab delimited textfile:

    0.227996254681648   0.337028824833703   0.238163571416268   0.183009231781289   0.085746697332588   0.13412895376826
    0.247891283973758   0.335555555555556   0.272129379268419   0.187328622765857   0.085921240923626   0.128372465534807
    0.264761012183693   0.337777777777778   0.245917821271498   0.183211905363232   0.080493183753814   0.122786059549795
    0.30506091846298    0.337777777777778   0.204265153911403   0.208453197418743   0.0715575291087 0.083682658454807
    0.222748815165877   0.337028824833703   0.209714942778068   0.084252659537679   0.142013573559938   0.234672985858848

I would like to read in every line and then print only the 6th column. This is working quite nice with this code:

with open('path/mytextfile.txt') as f:
    for line in f:
        header1 = f.readline()
        line = line.strip()
        columns = line.split()
        jmag = columns[5]
        print(jmag)
        if 'str' in line:
            break

It prints out the 6th column I want, but only prints every second row:

0.13412895376826
0.122786059549795
0.234672985858848
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-63-98c7449902b9> in <module>
      4         line = line.strip()
      5         columns = line.split()
----> 6         jmag = columns[5]
      7         print(jmag)
      8         if 'str' in line:

IndexError: list index out of range

What is the mistake here?

CodePudding user response:

cant you do something like

f = open("file.txt")
lines = readlines(f)
for line in lines:
    print(line.split()[5])
f.close()

this should take each line, and split them into 6 different numbers, then printing the 5th one in the list (which is the sixth number)

CodePudding user response:

The issue with your code is that you're doing for line in f: but also header1 = f.readline(). The for line in f: goes through each line, but the header1 = f.readline() removes the next line (and saves it into header1). All you have to do is remove the header1 = f.readline().

You can also be a little less wordy in the code by doing

with open("path/mytextfile.txt") as f:
    for line in f:
        columns = line.strip().split()
        if 'str' in line:
            break
        print(columns[5])

but it doesn't really matter.

I believe the index error is happening because the for line in f: finds out how many iterations it needs to go through, but f is changing size. It's generally a bad idea to change the size of a list or file as you're going through it.

  • Related