Python: find defined text string in a file, and replace the whole line
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Python: find defined text string in a file, and replace the whole line
Heya I really hope one or two python people are around. I've been looking around lately on the net for a solution to my problem. I want to mess with conf files on my system. Now they are meant to change values, therefore I can't exactly know what string I search for..
I've written something that finds and replaces a certain string in one file. All I found on the net was something that made a copy of the file and wrote the changes into the copy... So I made this, I couldn't get open("foo.txt", "r+w") to work for me
Code:
#! /usr/bin/python
# Preliminary code sample to start with..
import fileinput, string, sys
fileQuery = "usage.py"
sourceText = '''IPADDR[0]=""'''
replaceText = '''IPADDR[0]="192.168.1.102"'''
def replacemachine(fileName, sourceText, replaceText):
##################################################################
file = open(fileName, "r") #Opens the file in read-mode
text = file.read() #Reads the file and assigns the value to a variable
file.close() #Closes the file (read session)
file = open(fileName, "w") #Opens the file again, this time in write-mode
file.write(text.replace(sourceText, replaceText)) #replaces all instances of our keyword
# and writes the whole output when done, wiping over the old contents of the file
file.close() #Closes the file (write session)
print "All went well, the modifications are done"
##################################################################
replacemachine(fileQuery, sourceText, replaceText)
Now this would ONLY work if IPADDR[0] is = "" like what i search for... Is there a way to make a special sign that represents anything just like * does in bash ?
I know you can use variables inside a string like:
variableNeeded= cow
variable = "I love %s" % (variableNeeded)
Anyway I really hope to hear from anyone cause I am out of ideas (if the solution is followed up with a few links to places with lots of python info I wouldn't complain either :P )
Well, first of all, sed is probably a better tool for this, but ...
Code:
f = file(fileName)
newlines = []
for line in f:
if 'IPADDR[0]' in line:
# do the replacing here
newlines.append(line)
outfile = file(outfileName, 'w')
outfile.writelines(newlines)
alternately, instead of using "if 'IPADDR[0]' in line" you could use a regexp on the line if you wanted.
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if "IPADDR[0]" in line:
line=line.replace(<old>,<new>)
print line
Here's another solution:
Code:
bbox33:trunk $ python
Python 2.4.4 (#1, May 9 2007, 11:05:23)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import scriptutil as SU
>>> SU.freplace('.',
... shellglobs=('file',),
... regexl=((r'IPADDR\[0\]', 'IPADDR[0]="192.168.1.102"', None),))
1
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.