替换并覆盖而不是追加

问题描述 投票:0回答:7

我有以下代码:

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

python replace
7个回答
162
投票

在写入之前,您需要

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))

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

顺便说一句,这与 Python 并没有真正的关系。解释器调用相应的低级API。该方法

truncate()
在 C 编程语言中的工作方式相同:参见 http://man7.org/linux/man-pages/man2/truncate.2.html


133
投票
file='path/test.xml' 
with open(file, 'w') as filetowrite:
    filetowrite.write('new content')

以“w”模式打开文件,您将能够替换其当前文本,并用新内容保存文件。


23
投票

使用

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()

5
投票
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

我遇到了类似的问题,我没有使用不同的“模式”覆盖现有文件,而是在再次使用它之前删除了该文件,这样就好像我在每次运行时都附加到一个新文件代码。


3
投票

参见如何替换文件中的字符串以简单的方式工作,并且是与

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()

1
投票

在我的例子中,以下代码成功了

with open("output.json", "w+") as outfile:  #using w+ mode to create file if it not exists. and overwrite the existing content
    json.dump(result_plot, outfile)

0
投票

使用 python3 pathlib 库:

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))
© www.soinside.com 2019 - 2024. All rights reserved.