Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search and replace is adding not replacing

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading