替换和覆盖而不是附加 [英] Replace and overwrite instead of appending

查看:47
本文介绍了替换和覆盖而不是附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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",即我的旧内容后面跟着新的替换"内容.我该怎么做才能删除旧的东西而只保留新的东西?

where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?

推荐答案

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

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:

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') 再次打开它:

The other way is to read the file then open it again with 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))

truncateopen(..., 'w') 都不会改变 inode 文件的编号(我测试了两次,一次使用 Ubuntu 12.04 NFS,一次使用 ext4).

Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).

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

By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html

这篇关于替换和覆盖而不是附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆