reading and writing back to the same file

lamujerecc alr2 at
Fri May 25 18:22:27 CEST 2001

I know this topic has been rehashed, but I cannot get this to work. 
Here is the desired effect:

1) read from a file given by the user (working)
2) search the file for certain items and reformat (working)
3) write the modified file back to the target file (not
working...currently I   have an "out.txt" file hardcoded to test the
other items with - cheap, I know)

Here is my starting point code (all my attempts to write back to the
file I scrapped):

import sys
import string

if __name__ == "__main__" :
    # get target file from command line
    if len (sys.argv) > 1:
            f = open(sys.argv[1], "r+")
            OUT = open("out.txt","w")
            print "No file named %s exists!" % (sys.argv[1],)

        # read it and reformat
        while 1:
            t = f.readline()
            if t == '' :

            # write to OUT file and to the sys.stdout (for testing)
            sys.stdout.write(t + '\n')
            OUT.write(t+ '\n')

        # close it up

Thanks in advance for any advice you give!


More information about the Python-list mailing list