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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jul 14 00:40:27 EDT 2007


En Fri, 13 Jul 2007 23:46:24 -0300, J. J. Ramsey <jjramsey at pobox.com>  
escribió:

> In Perl, there is a module called "Tie::File". What it does is tie a
> list to each line of a file. Change the list, and the file is
> automatically changed, and on top of this, only the bits of the file
> that need to be changed are written to disk. At least, that's the
> general idea.

That usually means, rewriting from the first modified line to the end of  
the file.

> I was wondering if something roughly similar could be done in Python,
> or at the very least, 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.

Simplest aproach:

lines = list(open("myfile.txt"))
del lines[13]
lines[42] = "Look ma! Replacing line 42!\n"
open("myfile.txt","w").writelines(lines)

This of course reads the whole file in memory, but it's a compact way if  
you require random line access.
If you can serialize the file operations, try using the fileinput module  
with inplace=1.

(Having a true Tie::File implementation for Python would be a nice  
addition to the available tools...)

-- 
Gabriel Genellina




More information about the Python-list mailing list