Python first reads and then writes the content of the update file

Requirements: openread + modify + write at one time, the modified content overwrites the pre-modified

# r+读写且文件指针位于文件开始
# 这里不可用w+,否则读不到旧的文件内容
f = open('test.txt', 'r+')

content = f.read()

# 修改文件内容
content = str(int(content) + 1)

# 移动文件指针到文件开头
f.seek(0)
# 删除从当前文件指针到文件末尾的所有内容
f.truncate()

f.write(content)

f.close()

Guess you like

Origin blog.csdn.net/weixin_44559752/article/details/128525370
Recommended