reading and writing back to the same file

Joe Murray jmurray at agyinc.com
Fri May 25 15:59:47 EDT 2001


lamujerecc 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)
> 
> Here is my starting point code (all my attempts to write back to the
> file I scrapped):
> 
> #!/usr/local/bin/python
> import sys
> import string
> 
> if __name__ == "__main__" :
>     # get target file from command line
>     if len (sys.argv) > 1:
>         try:
>             f = open(sys.argv[1], "r+")
>             OUT = open("out.txt","w")
>         except:
>             print "No file named %s exists!" % (sys.argv[1],)
>             sys.exit(0)
> 
>         # 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
>         f.close()
>         OUT.close()
> 
> Thanks in advance for any advice you give!
> 
> -Lamujercc
> --
> http://mail.python.org/mailman/listinfo/python-list

Check out the fileinput module at python docs...

http://www.python.org/doc/current/lib/module-fileinput.html

It may be useful.

Cheers,

joe

-- 
Joseph Murray
Bioinformatics Specialist, AGY Therapeutics
290 Utah Avenue, South San Francisco, CA 94080
(650) 228-1146




More information about the Python-list mailing list