Python 替换并覆盖,而不是追加

Python 替换并覆盖,而不是追加,python,replace,Python,Replace,我有以下代码: 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<x

我有以下代码:

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()
重新导入
#打开xml文件进行读取:
file=open('path/test.xml','r+'))
#转换为字符串:
data=file.read()
file.write(re.sub(r“ABC(\s+)(.*)”,r“ABC\1\2”,数据))
file.close()文件
我想用新内容替换文件中的旧内容。但是,当我执行代码时,会附加文件“test.xml”,也就是说,旧内容后面跟着新的“替换”内容。要删除旧内容而只保留新内容,我可以做些什么?

在写入之前,您需要先删除文件的开头部分,然后使用,如果您要执行就地替换:

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()
无论是
truncate
还是
open(…,'w')
都不会改变文件的编号(我测试了两次,一次使用Ubuntu 12.04 NFS,一次使用ext4)

顺便说一下,这与Python并没有太大关系。解释器调用相应的低级API。方法
truncate()

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    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()
重新导入
#打开xml文件进行读取:
将open('path/test.xml','r+')作为f:
#转换为字符串:
data=f.read()
f、 搜索(0)
f、 写入(关于sub(r“ABC(\s+)(.*)”,r“ABC\1\2”,数据))
f、 截断()
在“w”模式下打开文件,您将能够替换其当前文本,并使用新内容保存文件

import os#must import this library
if os.path.exists('TwitterDB.csv'):
        os.remove('TwitterDB.csv') #this deletes the file
else:
        print("The file does not exist")#add this to prevent errors
我也遇到了类似的问题,我没有使用不同的“模式”覆盖现有文件,而是在再次使用之前删除了该文件,这样就好像每次运行代码时都要附加到一个新文件一样

See from以一种简单的方式工作,是一个与
replace

fin = open("data.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
    fout.write(line.replace('pyton', 'python'))

fin.close()
fout.close()
使用python3库:

重新导入
从pathlib导入路径
进口舒蒂尔
copy2(“/tmp/test.xml”,“/tmp/test.xml.bak”)#创建备份
filepath=Path(“/tmp/test.xml”)
content=filepath.read\u text()
filepath.write_text(re.sub(r“ABC(\s+)(.*)”,r“ABC\1\2”,content))
使用不同备份方法的类似方法:

from pathlib import Path

filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
从pathlib导入路径
filepath=Path(“/tmp/test.xml”)
filepath.rename(filepath.with_后缀('.bak'))#不同的备份方法
content=filepath.read\u text()
filepath.write_text(re.sub(r“ABC(\s+)(.*)”,r“ABC\1\2”,content))

当您说“用新内容替换文件中的旧内容”时,您需要读入并转换当前内容
data=file.read()
。你不是说“不需要先读就盲目地覆盖它”。这是一种清除文件并向其写入新内容的好方法,但问题在于读取文件、修改内容并用新内容覆盖原始内容。@Boris,首先读取文件,然后使用此答案中的代码有什么问题?@Rayhunter:效率很低。它简单有效,工作做得很完美。
seek
truncate
!!!我不明白为什么
seek
单独工作不起作用。
无论是截断还是打开(…,'w')都不会更改文件的inode编号
为什么重要?@rok如果inode更改或不更改在大多数情况下都不相关。仅在使用硬链接的边缘情况下,但是使用“f.seek()…”方法比使用“with open(…)”方法有缺点吗?
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
    fout.write(line.replace('pyton', 'python'))

fin.close()
fout.close()
import re
from pathlib import Path
import shutil

shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
from pathlib import Path

filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))