简体   繁体   中英

python file reading list index error: index out of range

I run into an error with the following code:

h = 0
num = 0
with open('file1') as f:

    for row in f.readlines():
        line = row.split()

        print(line)

        # check for new
        if int(float(line[0])) != h:
            h = int(float(line[0]))
            num += 1

OUTPUT:

['3', '1', '35', '31.924847576898625', '5.128603105085375', '6.20101', '0.7821899999999999', '0.23388931803044988']
[]
Traceback (most recent call last):
  File "phase_one.py", line 45, in <module>
    if int(float(line[0])) != h:
IndexError: list index out of range

Why is it when I call print(), the actual line is printed, but also there is an empty list '[]' printed after, which is causing this error?

There are two lines in your file. The first line is the first row. The second line of your file is blank. Either

  1. remove that line
  2. Or, check to see if line is empty before trying to access its first element. Empty lists are falsy, so you can simply do if line and int(line[0])... and short-circuiting will take care of the rest.
line = row.split()
print(line)

if line and int(line[0]) != h:
    h = int(line[0])
    num += 1
  1. Or, catch the error that is thrown.
line = row.split()
print(line)

try:
    if int(line[0]) != h:
        h = int(line[0])
        num += 1
except IndexError:
    pass

Also, you don't need to convert the string to float before converting it to int . Simply if int(line[0]):= h: should be sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM