简体   繁体   中英

Why does file.write() add an extra string at the end?

I was updating a text file with python (3.6), with open r+

with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.write(result)

by doing this, I get an unexpected extra ending part

</soap:Envelope>ap:Envelope>

of course the extra part is after the first closing >

I fixed this by doing

with open(f+'.play', 'r+') as f2:
  play = f2.read()
  result = manipulate(play)
  print(result)
  f2.seek(0, 0)
  f2.truncate()
  f2.write(result)

in this case the write works as I expect.

Nevertheless I do not understand why I need to truncate, is the seek(0,0) not enough? because in my mind seek(0) + write should be overwrite the whole content in a proper way, what piece of knowledge am I missing here?

If your old content has bigger size than one you are writing, the extra part will stay in the file. When you call seek(0, 0) you go to the beginning and start writing from there byte by byte, but the old data is not removed. When you call truncate() you remove old data, so it works as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM