0

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

2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Beat_Slayer
1
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 question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.