Mikel.JKK Mikel.JKK - 11 months ago 50
Python Question

String Index Out Of Range When Reading Text File

I keep on getting this error on the second last line of my program , and I am not sure why , all I am doing is reading a line from a text file.

if (items[0]) == 86947367 :
with open("read_it.txt") as text_file:
price = int(text_file.readlines()[2])
except ValueError:
new_price = int(price * (items2[0]))
product = (text_file.readline()[1])

Answer Source

When you use readlines(), your "cursor" in the file reaches the end. If you call it a second time, it'll have nothing left to read.

To avoid this behavior, you can store readlines() in a variable for multiple uses, or use text_file.seek(0) to put your cursor back at the beginning of the file.