[Tutor] Replacing the string in a file

Dave Angel davea at ieee.org
Fri Jan 22 12:23:53 CET 2010



vanam wrote:
> Thanks for your mail.
>
> As you have suggested i have  changed the mode to 'rw' but it is
> throwing up an error as below
>
> *******************
> IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt'
> *******************
> I am using python 2.6.4.
>
> But Script is managed to pass with 'a+' mode/r+ mode.
>
> log = open('data.txt','r+/a+')
> for x in log:
>      x = x.replace('Python','PYTHON')
>      print x,
> log.close()
>
> It had properly written and replaced Python to PYTHON.
>
> Thanks for your suggestion.
>
>   
> <snip>
>   
That won't work.  Better test it some more.  Without some form of 
write() call, you're not changing the file.


There are several workable suggestions in this thread, and I think 
fileinput is the easiest one.

DaveA



More information about the Tutor mailing list