How to replace text in file using Python [closed]
I would like to replace text from a source file using Python and save the new body of text to a new file. For example if a file has this text:
Today is Sunday and tomorrow is Monday
I would like to replace just the words in the middle without changing the entire line like this:
[Today is] Tuesday and yesterday was [Monday]
I would like to replace individual or group of words instead of the whole line.
I tried using this code:
with open(inputPath,"r") as fin: with open(outputPath,"w") as fout: for aline in fin: new_data = aline if new_data.startswith("""set interfaces ge-0/0/14"""): new_data = """coffee interface 1/1"
I am using Visual Studio Code. Thank you!
Solution 1:
You can use the following snippet to solve your problem.
with open("source.txt", "rt") as fin:
with open("destination.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('Sunday and tomorrow is', 'Tuesday and yesterday was'))
Open the source file in read mode and destination file in write mode. With help of replace() method in python, we can easily find and replace the word.