1

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?

2
  • 3
    Don't use .readlines, which must pre-read the entire file to a list before iteration can begin; iterate directly over the file object for line in f: as it's generally much more efficient stackoverflow.com/a/3541231/4541045 .. sometimes reading the whole file before doing other work does make sense (for example if you are going to write something to the end of it based upon some contents), but there is no need in this case Commented Jan 15, 2021 at 16:10
  • 1
    What does "check for new" mean? Your current code only tests against the previously seen value. Are you trying to get all the unique values from the first column in the file? For that, you should use a set or dict. Commented Jan 15, 2021 at 17:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.