Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unread a line in python

Tags:

python

file-io

I am new to Python (2.6), and have a situation where I need to un-read a line I just read from a file. Here's basically what I am doing.

  for line in file:
     print line
     file.seek(-len(line),1)
     zz = file.readline()
     print zz

However I notice that "zz" and "line" are not the same. Where am I going wrong?

Thanks.

like image 457
user721975 Avatar asked May 01 '11 17:05

user721975


2 Answers

I don't think for line in file: and seek make a good combination. Try something like this:

while True:
    line = file.readline()
    print line
    file.seek(-len(line),1)
    zz = file.readline()
    print zz

    # Make sure this loop ends somehow
like image 121
Gustav Larsson Avatar answered Nov 15 '22 19:11

Gustav Larsson


You simply cannot mix iterators and seek() this way. You should pick one method and stick to it.

like image 44
David Heffernan Avatar answered Nov 15 '22 19:11

David Heffernan