[Tutor] writing changes to a file

Wesley J. Chun wesc@alpha.ece.ucsb.edu
Wed, 9 Feb 2000 03:52:17 -0800 (PST)

    > Date: Wed, 9 Feb 2000 20:30:36 +0900
    > From: Craig Hagerman <craig@osa.att.ne.jp>
    > Hope this isn't too elementary: I need some guidance in how to open and
    > existing file, write some changes to it and then then close it. So far I
    > have been creating a new file for the changed version like this:
    > input = open('file_one','r')
    > output = open('file_two','w')
    > However,  I don't always need to have two files. I only want to change all
    > instances of "x" to "y", or perhaps add some new lines to the existing
    > file, and then save the new version. Is it possible to open a file to write
    > some changes to it in one go?


your quandry can be repeated across other languages as well,
not just Python.  depending on your situation, you can approach
them differently:

1) changing all instances of 'x' to 'y' (and similar)

if you have a text file (as opposed to a binary), this sounds
like a situation that calls for a simple filter than scans for
a particular string and replaces it with another.  you can ac-
complish this in Python, Perl, awk, or a unix shell script that
calls the 'sed' utilities.  if you want to do this in Python,
check out the 're' modules, which you can use to describe a
pattern to look for, as well as one to substitute with.

2) add some new lines to an existing file

if you want to just append to an existing file, use the append

	f = open(your_file, 'a')

if you want to both read *and* write to your existing file, use
update mode:

	f = open(your_file, 'r+')

the '+' means open the file for reading and writing, i.e.
update.  ('w+' means delete the existing file and open a new
one for read and write so be careful!) anyway, once you open
the file, you can use f.seek() and f.tell() to navigate within
the file.  if you are going to read and write to your file,
make sure you explicitly f.flush() between change of operations.

hope this helps!


cyberbweb.consulting :: silicon.valley, ca