I am trying to find a way to search a filename.rc file for a particular string. For now lets just say I am searching for the string PARTYHOST. After finding PARTYHOST in the file I would like to replace anything after it(so 192.168.0.1) with a new string which I have stored. Then it should continue on looking for other instances of this and do the same thing until the end of file. Anyone have some suggestions or example code to solve this?


Example (filename.rc)

jibberjabber
PARTYHOST 192.168.0.1
jibberjabber
LANHOST 192.168.0.10
Jibberjabber
PARTYHOST 192.168.0.1

Recommended Answers

All 3 Replies

f = open('filename.rc')
old_rc = f.readlines()
f.close()

host = 'PARTYHOST'
new_ip = '127.0.0.1'
f = open('filename.rc', 'w')
for i in range(len(old_rc)):
    if old_rc[i].find(host) != -1:
        f.write('%s %s\n' % (host, new_ip)) #You should check the newline
    else:
        f.write(old_rc[i])
f.close()

This worked perfectly and probably saved me 2+ hours. Thank you sir

Your welcome.

Happy to help!

You can close the thread marking it as solved.

Cheers, and happy coding!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.