Reputation: 63
I have a code where I can write in to the same file but I want to write in to a new file so the first file should be constant.
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)
Upvotes: 0
Views: 59
Reputation: 2947
You can use the library shutil
to copy a file to the target location. You can do the modification on the copied file then. Detailed documentation on shutil
is here.
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)
Upvotes: 0
Reputation: 27557
You can try the copyfile
method from the shutil
module:
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)
Upvotes: 1