簡體   English   中英

如何替換文本文件中的字符串並將其保存到新文件中?

[英]How to replace String in a textfile and save it to a new file?

我有一個代碼,我可以寫入同一個文件,但我想寫入一個新文件,所以第一個文件應該是不變的。

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)

您可以嘗試從shutil模塊中的copyfile方法:

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)

您可以使用庫shutil將文件復制到目標位置。 然后您可以對復制的文件進行修改。 關於shutil詳細文檔在這里

import shutil

original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be copied\file name.file extension'

shutil.copyfile(original, target)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM