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)
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)
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)
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)