text file edit object
Skip Montanaro
skip at pobox.com
Fri Jul 11 08:57:51 EDT 2003
Facundo> What about something like this:
Facundo> try:
Facundo> infile = file("foo.txt", "r")
Facundo> lines = infile.readlines()[:-10]
Facundo> infile.close()
Facundo> outfile = file("foo.txt.new", "w")
Facundo> outfile.writelines(lines)
Facundo> outfile.close()
Facundo> except:
Facundo> print >> sys.stderr, "edit failed"
Facundo> raise
Facundo> else:
Facundo> os.rename("foo.txt2", "foo.txt")
Yes, that's what I thought of first, however the errors (and how you recover
from them) are different between the reading and writing phases.
Facundo> One question: is this method (file, readlines) efficient on big
Facundo> files?
Should be, though you have the obvious overhead of gulping the entire file.
For very large files it would probably be more efficient to read the file in
smaller chunks and only avoid writing the last ten lines. However, the code
gets that much more baroque. ;-)
Skip
More information about the Python-list
mailing list