Reading a file and resuming reading.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri May 25 09:51:39 EDT 2007


In <mailman.8170.1180100553.32031.python-list at python.org>, Karim Ali
wrote:

> 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;
> -----------------------------

while True:
    line = f.readline()
    if not line:
        break
    # Do something with `line`.

> 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++).

Both look ugly to Pythonistas too.  Files are iterable:

for line in f:
    # Do something with `line`.

> 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!

for line_nr, line in enumerate(f):
    # Do something with `line_nr` and `line`.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list