Can I change one line in a file without rewriting the whole thing?

greg greg at cosc.canterbury.ac.nz
Sat Jul 14 02:54:56 EDT 2007


J. J. Ramsey wrote:
> if I can avoid doing what amounts to reading the
> whole file into memory, changing the copy in memory, and writing it
> all out again.

Except in very special circumstances, not really.
If you do anything that makes a line longer or
shorter, everything after that line in the file
needs to be re-written, one way or another.

If you're doing this sort of thing a lot, and
need it to be faster than reading and rewriting the
file, you may need to look into using a more
sophisticated format on disk than a plain file.

--
Greg



More information about the Python-list mailing list