How can I edit the system configuration file using Python with following specifications
- it should not change the format of the config item on how it looks
- we should not edit the commented config item
- if that config item is not there, it should add a entry
**I have used regex to achieve this so far, But I am facing some formatting issues, and I end up in changing the commented config items. **
def change_config(key, value):
with open("/etc/sysctl.conf", "r+") as f:
content = f.read()
if key in content:
for line in fileinput.input("/etc/sysctl.conf", inplace=1):
line = re.sub(r''+key+'=\d', key+'='+value, line.rstrip())
print line
else:
f.write(key+"="+value+"\n")
Configuration files looks like this
default:
fsize = 2097151
core = 2097151
cpu = -1
data = 262144
rss = 65536
stack = 65536
nofiles = 2000
or sometimes without intent like this
fsize = 2097151
core = 2097151
cpu = -1
data = 262144
please help me in improve the same code. I should not use libraries like PythonConfigParser or something.