LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Python: find defined text string in a file, and replace the whole line (http://www.linuxquestions.org/questions/programming-9/python-find-defined-text-string-in-a-file-and-replace-the-whole-line-186924/)

Dark Carnival 05-28-2004 09:06 AM

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 )

Thanks in advance, and for your time!

kooch 05-28-2004 11:47 AM

Python has a regular expressions module. Check out python.org/doc for pretty much all the documentation you'll ever need.

Strike 05-28-2004 11:55 AM

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.

lilaz 05-21-2007 02:42 AM

Hello,

you may want to check out the scriptutil.py module.

It is providing functions for file searching and in-line string search/replace.

ghostdog74 05-21-2007 04:02 AM

Code:

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if "IPADDR[0]" in line:
        line=line.replace(<old>,<new>)
        print line


lilaz 05-22-2007 04:47 AM

to ghostdog74: thank you very much for pointing out the fileinput module!

Python indeed comes with the batteries included :)

The freplace() function (description here) should probably be refactored to make use of the fileinput module.

lilaz 05-22-2007 06:02 AM

Quote:

Originally Posted by ghostdog74
Code:

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

The freplace() function is described here.


All times are GMT -5. The time now is 04:01 AM.