Search and replace is adding not replacing

Question:

I am trying to find this string in a file:

/home/pi/dew-heater/get-temp.py 

And replace it with

#/home/pi/dew-heater/get-temp.py

But there are cases where it already reads #/home/pi/dew-heater/get-temp.py. So my program is replacing it with a double ## so it looks like this:

##/home/pi/dew-heater/get-temp.py 

How can I prevent the double ## ??

with open('/home/pi/dew-heater/getweather.sh', 'r') as fp:
    data = fp.read()
    typos = data.replace('/home/pi/dew-heater/get-temp.py', '#/home/pi/dew-heater/get-temp.py')
with open('/home/pi/dew-heater/getweather.sh', 'w') as fp:
    fp.write(typos)
Asked By: BobW

||

Answers:

Use a regular expression with a negative lookbehind.

import re

with open('/home/pi/dew-heater/getweather.sh', 'r') as fp:
    data = fp.read()
    typos = re.sub(r'(?<!#)/home/pi/dew-heater/get-temp.py', '#/home/pi/dew-heater/get-temp.py', data)

with open('/home/pi/dew-heater/getweather.sh', 'w') as fp:
    fp.write(typos)
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.