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 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! |
Python has a regular expressions module. Check out python.org/doc for pretty much all the documentation you'll ever need.
|
Well, first of all, sed is probably a better tool for this, but ...
Code:
f = file(fileName) |
Hello,
you may want to check out the scriptutil.py module. It is providing functions for file searching and in-line string search/replace. |
Code:
import fileinput |
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. |
Quote:
Code:
bbox33:trunk $ python |
All times are GMT -5. The time now is 03:47 AM. |