Avatar of lessthan2
lessthan2
 asked on

Python script to search for and replace text in a file

Need help with a simple search and replace script in Python.
In my code, I want to open an HTM file, find "McHugh" and replace it with "REPLACED12345".

#!/usr/bin/python
import string,  os, sys

f = open('sig.txt', 'r')
file_contents = f.readlines()
f.close()

f = open('sig.htm', 'w')
text1 = ("McHugh")
text2 = ("REPLACED12345")

for text1 in 'sig.htm'
        f.write(text1.replace(text1, text2))
f.close()

Open in new window


500 points guys. Just need it to use as a template to save me time. Thanks
Python

Avatar of undefined
Last Comment
Sudaraka Wijesinghe

8/22/2022 - Mon
lessthan2

ASKER
Here is a sample file to run the solution against.
sig.htm
ASKER CERTIFIED SOLUTION
Sudaraka Wijesinghe

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Sandeep Kothari

this should work...
 #!/usr/bin/python
import string,  os, sys

f = open([b]'sig.htm'[/b], 'r')
file_contents = f.read()
f.close()

f = open('sig.htm', 'w')
text1 = ("McHugh")
text2 = ("REPLACED12345")

f.write(file_contents.replace(text1, text2))
f.close()

Open in new window

Sandeep Kothari

this should work...the above code got some characters so ignore the above one...

try this..
 #!/usr/bin/python
import string,  os, sys

f = open('sig.htm', 'r')
file_contents = f.read()
f.close()

f = open('sig.htm', 'w')
text1 = ("McHugh")
text2 = ("REPLACED12345")

f.write(file_contents.replace(text1, text2))
f.close()

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
lessthan2

ASKER
This did the trick and taught me a valuable lesson at the same time. Thank you.
Sudaraka Wijesinghe

Glad to help. Thanks for the points.