Python clears the file and replaces the instance of the contents

  • 2020-12-26 05:49:51
  • OfStack

There is a text file that needs to be replaced with python to complete. I wrote it like this:


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

Execute the above function, and it appends, not replaces, the content.

f.truncate() didn't work. How should I write it?

You need to add f.seek (0) to locate the file to position 0. Without this sentence, the file is located to the end of the data, and truncate is also deleted from here, so it feels like it doesn't work.


def modify_text():
 with open('test.txt', "r+") as f:
  read_data = f.read()
  f.seek(0)
  f.truncate() # Empty file 
  f.write(read_data.replace('apple', 'android'))

Related articles: