Reading a file and resuming reading.
Hrvoje Niksic
hniksic at xemacs.org
Fri May 25 10:04:36 EDT 2007
"Karim Ali" <kakeez at hotmail.com> writes:
> -----------------------------
> while not eof <- really want the EOF and not just an empty line!
> readline by line
> end while;
> -----------------------------
for line in open_file:
...
It will stop on EOF, not on empty 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!
If you open the file in binary mode, you can easily keep track of the
position in file:
bytepos = 0
with file(filename) as f:
for line in f:
... process line ...
bytepos += len(line)
If you need to restart the operation, simply seek to the previously
known position:
# restart with old bytyepos
with file(filename) as f:
f.seek(bytepos)
for line in f:
... process line ...
bytepos += len(line)
More information about the Python-list
mailing list