Reputation: 17
I am attempting to replace text from a source file into a new file. The replacing of text works for one line, but a few lines down and I fail to replace text sitting in the middle of a statement.
Here is the source text. The words in brackets are what I am trying to replace, without changing the characters around the words:
[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"
This is what I would like to output:
interface x/x name "xxx"
(also adding quotations for the xxx text after "name")
However the output text replaces once, and then keeps three copies of the original text:
hostname "EX4300"
set system host-name EX4300
set system host-name EX4300
set system auto-snapshot
set system auto-snapshot
set system auto-snapshot
Here is my code:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('set system host-name EX4300', 'hostname "EX4300"'))
fout.write(line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address'))
Please let me know where I went wrong or if there is a better way of approaching this. I am using Visual Studio Code.
Upvotes: 0
Views: 105
Reputation: 28673
Only use 1 fout.write()
, call the replace function al often as you want.
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
fout.write(line)
Upvotes: 1