Skip to content

Instantly share code, notes, and snippets.

@tlatsas
Created July 11, 2013 15:18
Show Gist options
  • Save tlatsas/5976388 to your computer and use it in GitHub Desktop.
Save tlatsas/5976388 to your computer and use it in GitHub Desktop.
read plain configuration files (without ini sections) using ConfigParser into dictionaries (so we can easily change valies), then built a string to write to file
import ConfigParser
from collections import OrderedDict
class NoSectionConfig(object):
section = "dummy"
def __init__(self, fp):
self.fp = fp
self.section_head = "[{0}]\n".format(self.section)
def readline(self):
if self.section_head:
try:
return self.section_head
finally:
self.section_head = None
else:
return self.fp.readline()
cfg = ConfigParser.SafeConfigParser()
with open('main.cf', 'r') as f:
cfg.readfp(NoSectionConfig(f))
# config -> dict
data = OrderedDict(cfg.items(NoSectionConfig.section))
# dict -> string
s = []
for k,v in data.items():
s.append("{0} = {1}".format(k, v))
print("\n".join(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment