0

There is a text file,I want to replace a word with another one via python,
I do it like this:

demo.py

def modify_text():
    with open('test.txt', "r+") as f:
        read_data = f.read()
        f.truncate() 
        f.write(read_data.replace('apple', 'pear'))

running the function above, it will append the content into test.txt, the original content still exists, f.truncate() does not work, I want to remove original content, how can I do it?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
zwl1619
  • 4,002
  • 14
  • 54
  • 110

1 Answers1

4

truncate takes an optional size parameter that defaults to the current position, which is the end of the file, since you just read it all. So you're in fact truncating the file to its current size (which pretty much does nothing) and then appending the replaced data. You should truncate it to an empty file:

def modify_text():
    with open('test.txt', "r+") as f:
        read_data = f.read()
        f.truncate(0) 
        # Here ----^
        f.write(read_data.replace('apple', 'pear'))
Mureinik
  • 297,002
  • 52
  • 306
  • 350