python - 如何替换文本文件中的字符串并将其保存到新文件中?
问题描述
我有一个可以写入同一个文件的代码,但我想写入一个新文件,所以第一个文件应该是不变的。
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)
解决方案
您可以尝试模块中的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)
推荐阅读
- npm - 运行 npm install 不会产生锁定文件
- python - 在 python 中将文本文件读取到字典的问题
- wordpress - macOS 上的 XAMPP WordPress 权限
- css - 如何将 Materialise Tooltips 的位置更改为左上角?
- android-studio - Android Studio 无法正确自动完成导入
- php - PHP 文档根目录和要求
- r - 为什么 auto.arima() 给我错误:“'by' 参数太小了”
- c - 使用 exec 进行 IO 重定向
- mysql - 按日期和所有唯一值的总和分组
- python - 如何在列表中保存日期时间对象(python、csv)