Reading a file and resuming reading.

Laszlo Nagy gandalf at shopzeus.com
Fri May 25 09:50:57 EDT 2007


Karim Ali wrote:
> Hi,
>
> Simple question. Is it possible in python to write code of the type:
>
> -----------------------------
> while not eof  <- really want the EOF and not just an empty line!
>     readline by line
> end while;
> -----------------------------
>
> What I am using now is the implicit for loop after a readlines(). I don't 
> like this at all as a matter of opinion (my background is C++).
>
> But also, in case for one reason or another the program crashes, I want to 
> be able to rexecute it and for it to resume reading from the same position 
> as it left. If a while loop like the one above can be implemented I can do 
> this simply by counting the lines!
>
> I appreciate any help.
>   
What about this:

fin = file('test.txt','r')
for line in fin:
    process_line(line)

By the way, readline returns an empty line only at the end of the file. 
In all other cases, it will return a string that ends with a newline. 
E.g. you can detect if you are at the end of the file or not. But using 
the above snippet is usually better. Text files are iterable, line by line.

Best,

   Laszlo




More information about the Python-list mailing list