How to write at a particular position in text file without erasing original contents?

末鹿安然 提交于 2019-11-29 11:38:57

If the file is not particularly large, you can read its contents in memory as a string (or a list of lines), do the replacement and write the contents back. Something like this:

total = 'Total: __{}__'.format(12345)

with open(filename, 'r+') as f:
    contents = f.read().replace('Total: __00__', total)
    f.seek(0)
    f.truncate()
    f.write(contents)

Seek will only be useful if you are not changing the length of the file with the operation (that is: you leave enough bytes in the file at that location to write any possible total value). Otherwise you will have to re-write all bytes of the file that follow that point (because most file systems do not have an "insert" operation on files).

I'm guessing what you missed is opening the file in the correct mode to re-write it.

f = open(filename,"r+b")
f.seek(POSITION)
f.write(DATA)
f.close()

You will want to add appropriate error checking...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!