替换并覆盖而不是追加

2023-12-10

我有以下代码:

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”,即我有旧内容,后跟新的“替换”内容。我该怎么做才能删除旧的内容并只保留新的内容?


你需要seek写入之前到文件的开头,然后使用file.truncate()如果你想就地替换:

import re

myfile = "path/test.xml"

with open(myfile, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
    f.truncate()

另一种方法是读取文件然后再次打开它open(myfile, 'w'):

with open(myfile, "r") as f:
    data = f.read()

with open(myfile, "w") as f:
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))

Neither truncate nor open(..., 'w')将改变inode文件的编号(我测试了两次,一次使用 Ubuntu 12.04 NFS,一次使用 ext4)。

顺便说一句,这与 Python 并没有真正的关系。解释器调用相应的低级API。方法truncate()在 C 编程语言中的工作原理相同:参见http://man7.org/linux/man-pages/man2/truncate.2.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

替换并覆盖而不是追加 的相关文章

随机推荐