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?
.readlines, which must pre-read the entire file to a list before iteration can begin; iterate directly over the file objectfor 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