2

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:
            try:
                price = int(text_file.readlines()[2])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)
                price_list.append(new_price)
                product = (text_file.readline()[1])
                print(product)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • there is nothing more for the `readline()` to read since the `readlines()` read them all. – Ma0 Aug 30 '16 at 11:52
  • so can i read another line ? without the last 2 lines , my codes works great. ( this is only a chunk of my program) –  Aug 30 '16 at 11:53
  • No. you either read them all at once and store that somewhere to process it **or** you read it line by line and process the data as it comes – Ma0 Aug 30 '16 at 11:57
  • yes I am trying to read line by line , the only way I know how to do this is .readline(). I want my code to print out the price then the product in that order. –  Aug 30 '16 at 11:58
  • then why are you using `readlines()` with an 's' at the end? – Ma0 Aug 30 '16 at 12:30
  • but if I use .readline()[3] for example it print the 3rd letter not word. So the from the word banana , it will print n. –  Aug 30 '16 at 12:57
  • every instance of `readline()` is a string and as such it does exactly what you describe when indexed. to get the third line you have to execute `readline()` three times; once for every line. Normally, we don't do that. though. We try to look for patterns in a file. Btw `'banana'[3]` returns `'a'`. Python is 0-index – Ma0 Aug 30 '16 at 13:00

2 Answers2

1

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.

TrakJohnson
  • 1,755
  • 2
  • 18
  • 31
  • yes .seek() worked great thank you. so does this function just reset the "cursor" ? –  Aug 30 '16 at 13:10
  • @Mikel.JKK : .seek() just moves the cursor in your iterator at a certain position. If you need a more detailed answer, you can check this post : http://stackoverflow.com/questions/3266180/can-iterators-be-reset-in-python – Floran Gmehlin Aug 30 '16 at 13:14
0

problem:

price = int(text_file.readlines()[2])

the readlines() cause the readline() to return none or something like that. try to store readlines() in a tmp var and then

price = tmp[2]
product =tmp[1]
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
yosi
  • 25
  • 4