Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #40953

read and write the same text file

X-Received by 10.224.17.140 with SMTP id s12mr4243811qaa.3.1362843368719; Sat, 09 Mar 2013 07:36:08 -0800 (PST)
X-Received by 10.50.180.197 with SMTP id dq5mr322634igc.17.1362843368642; Sat, 09 Mar 2013 07:36:08 -0800 (PST)
Path csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!t2no132881qal.0!news-out.google.com!o5ni217qas.0!nntp.google.com!dd2no142812qab.0!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail
Newsgroups comp.lang.python
Date Sat, 9 Mar 2013 07:36:08 -0800 (PST)
Complaints-To groups-abuse@google.com
Injection-Info glegroupsg2000goo.googlegroups.com; posting-host=182.242.231.249; posting-account=Z1-aQQoAAADvnuKxr9sysEiuPIcBNfjX
NNTP-Posting-Host 182.242.231.249
User-Agent G2/1.0
MIME-Version 1.0
Message-ID <c41028f7-e457-4a2b-99f4-c473eaadd128@googlegroups.com> (permalink)
Subject read and write the same text file
From iMath <redstone-cold@163.com>
Injection-Date Sat, 09 Mar 2013 15:36:08 +0000
Content-Type text/plain; charset=ISO-8859-1
Content-Transfer-Encoding quoted-printable
Xref csiph.com comp.lang.python:40953

Show key headers only | View raw


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))

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

read and write the same text file iMath <redstone-cold@163.com> - 2013-03-09 07:36 -0800
  Re: read and write the same text file Roy Smith <roy@panix.com> - 2013-03-09 10:47 -0500
    Re: read and write the same text file Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-10 03:45 +0000

csiph-web