I need to edit a configuration file through python and i tried searching on stackoverflow and google and they don't cover my situation, since i need to replace lines in the file and perform matches in my search.
Also, what i found covers how to do it for one line, i will be performing at least 8 line replacements in the file and I would like to know if there is a cleaner and more elegant way of doing this than putting 10 replace(foo, bar) lines altogether.
I need to "match" lines like "ENABLEPRINTER", "PRINTERLIST", "PRNT1.PORT". I want to match thesse text and ignore whatever follows (ex: "=PRNT1, PRNT2").
So i would do something like
replace('ENABLEPRINTER', 'y')
replace('PRINTERLIST', 'PRNT3)
The file looks like this:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2
PRNT1.PORT=9600
PRNT1.BITS=8
Also note these files are about 100 lines and i need to edit about 10 of them.
Thank you very much for your help.
UPDATE:
Using the code posted by @J.F. Sebastian, i'm now getting the following error:
configobj.ParseError: Parse error in value at line 611.
Line 611 of the file is:
log4j.appender.dailyRollingFile.DatePattern='.'yyyy-MM-d
So the problem is with the ' character.
If I comment out that line, the script is working fine with the code posted by @J.F. Sebastian.
Before:
After:
Too simple to be definitive. Say what are the errors or weaknesses.
The advantage of regexes is they can be modulated easily to particular cases.
.
EDIT:
I've just seen that:
"what i want to do is assign a new value to the variable "
you could inform of that earlier !
Could you give an exemple of file before / after , please.
.
EDIT 2
Here's the code to change the values of certain variables in a file:
Before:
After:
If the file is in
java.util.Properties
format then you could usepyjavaproperties
:It is not very robust, but various fixes for it could benefit people who come next.
To replace multiple times in a short string:
To replace variables names in a configuration file (using
configobj
module):If by
replace('ENABLEPRINTER', 'y')
you mean assigny
to theENABLEPRINTER
variable then:It seems
configobj
is not compatible with:You could quote it:
Or:
Or
conf.update()
does something similar to: