LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-28-2004, 09:06 AM   #1
Dark Carnival
Member
 
Registered: Jun 2003
Posts: 166

Rep: Reputation: 30
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!
 
Old 05-28-2004, 11:47 AM   #2
kooch
Member
 
Registered: Mar 2004
Location: Upstate NY
Distribution: Slackware/YDL
Posts: 77

Rep: Reputation: 15
Python has a regular expressions module. Check out python.org/doc for pretty much all the documentation you'll ever need.
 
Old 05-28-2004, 11:55 AM   #3
Strike
Member
 
Registered: Jun 2001
Location: Houston, TX, USA
Distribution: Debian
Posts: 569

Rep: Reputation: 31
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.

Last edited by Strike; 05-28-2004 at 11:57 AM.
 
Old 05-21-2007, 02:42 AM   #4
lilaz
LQ Newbie
 
Registered: May 2007
Posts: 5

Rep: Reputation: 0
Hello,

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

It is providing functions for file searching and in-line string search/replace.
 
Old 05-21-2007, 04:02 AM   #5
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
Code:
import fileinput
for line in fileinput.FileInput("file",inplace=1):
    if "IPADDR[0]" in line:
        line=line.replace(<old>,<new>)
        print line
 
Old 05-22-2007, 04:47 AM   #6
lilaz
LQ Newbie
 
Registered: May 2007
Posts: 5

Rep: Reputation: 0
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.
 
Old 05-22-2007, 06:02 AM   #7
lilaz
LQ Newbie
 
Registered: May 2007
Posts: 5

Rep: Reputation: 0
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.
 
  


Reply

Tags
files, find, python, replace, search



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to replace a string in a text file jpan Linux - General 3 10-14-2012 06:17 PM
How to replace string pattern with multi-line text in bash script? brumela Linux - Newbie 6 04-21-2011 06:56 AM
Find and replace text in multiple file Bad_Bob Linux - Software 9 05-08-2008 02:31 AM
C++ text file line by line/each line to string/array Dimitris Programming 15 03-11-2008 08:22 AM
replace a string/number in a text file jpan Linux - General 3 10-22-2004 09:33 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:02 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration