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 fil
If the file is in java.util.Properties format then you could use pyjavaproperties:
from pyjavaproperties import Properties
p = Properties()
p.load(open('input.properties'))
for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
p[name] = value
p.store(open('output.properties', 'w'))
It is not very robust, but various fixes for it could benefit people who come next.
To replace multiple times in a short string:
for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
some_string = some_string.replace(old, new)
To replace variables names in a configuration file (using configobj module):
import configobj
conf = configobj.ConfigObj('test.conf')
for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
conf[new] = conf[old]
del conf[old]
conf.write()
If by replace('ENABLEPRINTER', 'y')
you mean assign y
to the ENABLEPRINTER
variable then:
import configobj
ENCODING='utf-8'
conf = configobj.ConfigObj('test.conf', raise_errors=True,
file_error=True, # don't create file if it doesn't exist
encoding=ENCODING, # used to read/write file
default_encoding=ENCODING) # str -> unicode internally (useful on Python2.x)
conf.update(dict(ENABLEPRINTER='y', PRINTERLIST='PRNT3'))
conf.write()
It seems configobj
is not compatible with:
name = '.'something
You could quote it:
name = "'.'something"
Or:
name = '.something'
Or
name = .something
conf.update()
does something similar to:
for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
conf[name] = value