read and write the same text file

Roy Smith roy at panix.com
Sat Mar 9 10:47:34 EST 2013


In article <c41028f7-e457-4a2b-99f4-c473eaadd128 at googlegroups.com>,
 iMath <redstone-cold at 163.com> wrote:

> read and write the same text file 
> Open a text file ,read the content ,then make some change on it ,then write 
> it back to the file ,now the modified text  should only has the modified 
> content but not the initial content ,so can we implement this by only set the 
> mode parameter with open() function ?if yes ,what the parameter should be ?if 
> no ,can we implement this by only one with statement ?
> I implement this with 2 with statement as the following 
> 
> replace_pattern = re.compile(r"<.+?>",re.DOTALL)
> 
> def text_process(file):
> 
>     with open(file,'r') as f:
>         text = f.read()
> 
>     with open(file,'w') as f:
>         f.write(replace_pattern.sub('',text))

At a minimum, you need to close the file after you read it and before 
you re-open it for writing.

There's a variety of ways you could achieve the same effect.  You might 
open the file once, in read-write mode, read the contents, rewind to the 
beginning with seek(), then write the new contents.  You might also 
write the modified data out to a new file, close it, and then rename it.  
But, open, read, close, open, write, close is the most straight-forward.



More information about the Python-list mailing list