Editing files

Alex Martelli aleaxit at yahoo.com
Thu Dec 21 09:56:47 EST 2000


"dv" <lars at stea.nu> wrote in message
news:Bdd06.5591$K6.674078 at juliett.dax.net...
> I'm trying to automate some configuration tasks with python. Is it
possible
> to do a "search and replace" or specify where (which line) in a file
python
> will write?

In modern systems (Unix, Linux, Windows, Mac, ...) files are not
internally 'line oriented', but rather byte-oriented.  So, you
can specify the *byte* offset (with a file object's "seek" method),
but not (easily or directly) "which line".

For files that are not too huge, BY FAR the simplest thing is to
get them all into memory as a list of lines, in one go:

    thelines = thefile.readlines()

now you can modify the lines with great ease, and no problem
at all, and finally write them all out back to the file, after
a thefile.seek(0) to be sure [so you'll write from the start!].
thefile.writelines(thelines) will do it.

Having the file be readable AND rewritable requires opening it
with a "r+" option, by the way, right at the start:
    thefile = open("what.txt","r+")

So, putting it all together, it's simple indeed:

    thefile = open("what.txt","r+")
    thelines = thefile.readlines()
    #
    # here, change thelines as you wish
    #
    thefile.seek(0)
    thefile.writelines(thelines)
    thefile.truncate()
    thefile.close()

The .truncate is only needed if you may have shortened the
total number of bytes in thelines, and it won't be OK on
ALL platforms (but I think Windows and Linux support it).


You may be selective in your _rewriting_, with a little
effort -- overwriting just SOME specific lines -- but that
will work only if your modifications never change the
length of any line, which is quite a rare situation --
probably not worth worrying about.  And you do have to
read the file at the start, to learn the byte offsets
at which the various lines start, so the memory taken/
computer effort doesn't change much, while programming
it IS more complex.  So, I'd skip it, if feasible.


Alex






More information about the Python-list mailing list