reading and writing back to the same file

Neil mac4-devnull at theory.org
Sat May 26 03:44:32 EDT 2001


In article <aeb7bf53.0105250822.22c5ac1d at posting.google.com>, "lamujerecc"
<alr2 at cec.wustl.edu> wrote:

> 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)
What wrong with hardcoding a value temporarily? If you know your going to
change it later, its all good.


Why don't you just read the entire file into a list, close the stream,
then open an output stream to write to?  Is the file really large or
something? 

I modified your code below to how I would do it. I left out the
exceptions because It just clutters the example....

#!/usr/local/bin/python
import sys
import string
 
if __name__ == "__main__" :
    # get target file from command line
    if len (sys.argv) > 1:
        f = open(sys.argv[1], "r")
        data = f.readlines() #### note the multiple lines...
        f.close()

        f = open(sys.argv[1]. "w")
        for t in data:
            # do stuff to t....
            t = string.split(t)
            ...

            f.write( t+ '\n')
        f.close()

Hope that helps.

Neil Macneale

PS: if you want to reply by email, remove the '-devnull' from my email.



More information about the Python-list mailing list