首页 > 解决方案 > 如何替换文本文件中的字符串并将其保存到新文件中?

问题描述

我有一个可以写入同一个文件的代码,但我想写入一个新文件,所以第一个文件应该是不变的。

from pathlib import Path
filename ="input.txt"
outputfile = "output.txt"
text_to_search_old1 = input("const String roomname_short:(old): ");
replacement_text_new1 = input("const String roomname_short:(new): ");
text_to_search_old2 = input("const String roomname_short:(old): ");
replacement_text_new2 = input("const String roomname_short:(new): ");

path = Path(filename)
path2 = Path(outputfile)
text = path.read_text()
text2 = path.read.text()
text = text.replace(text_to_search_old1, replacement_text_new1)
text = text.replace(text_to_search_old2, replacement_text_new2)
path.write_text(text2)

标签: python

解决方案


您可以尝试模块中的copyfile方法shutil

from pathlib import Path
from shutil import copyfile

filename = "input.txt"
outputfile = "output.txt"

copyfile(filename, outputfile)

text_to_search_old1 = input("const String roomname_short:(old): ");
replacement_text_new1 = input("const String roomname_short:(new): ");
text_to_search_old2 = input("const String roomname_short:(old): ");
replacement_text_new2 = input("const String roomname_short:(new): ");

path = Path(outputfile)
text = path.read_text()
text = text.replace(text_to_search_old1, replacement_text_new1)
text = text.replace(text_to_search_old2, replacement_text_new2)
path.write_text(text)

推荐阅读