我有以下代码:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
我想用新内容替换文件中的旧内容。然而,当我执行我的代码时,附加了文件“test.xml”,即旧内容后面跟着新的“替换”内容。我该怎么做才能删除旧的东西并只保留新的东西?
原文由 Kaly 发布,翻译遵循 CC BY-SA 4.0 许可协议
你需要
seek
在写入之前到文件的开头然后使用file.truncate()
如果你想做就地替换:另一种方法是读取文件,然后使用
open(myfile, 'w')
再次打开它:truncate
和open(..., 'w')
都不会更改文件的 inode 编号(我测试了两次,一次使用 Ubuntu 12.04 NFS,一次使用 ext4)。顺便说一句,这与 Python 并没有真正的关系。解释器调用相应的低级 API。方法
truncate()
在 C 编程语言中的工作原理相同:参见 http://man7.org/linux/man-pages/man2/truncate.2.html