iMath
iMath

Reputation: 2478

read and write the same text file

What I want to do:

Now the modified text should only has the modified content but not the initial content.

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

Upvotes: 2

Views: 494

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

If you want to replace the text in a file with the 'fixed' version, you have to either re-open the file, or open it in r+ (read + write) mode and truncate before writing:

with open(file,'r+') as f:
    text = f.read()
    f.seek(0)
    f.truncate()
    f.write(replace_pattern.sub('',text))

If you do not truncate the file first, then you run the risk of writing out too few new bytes. You read foo bar baz and write out foo spam, then your file ends up as foo spambaz as the old data is not removed and was longer.

Upvotes: 3

Related Questions