471,330 Members | 1,662 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

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

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.

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.

Jul 14 '07 #1
1 2975
En Fri, 13 Jul 2007 23:46:24 -0300, J. J. Ramsey <jj******@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

Jul 14 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by nan | last post: by
18 posts views Thread by John Bailo | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.