Reputation: 433
I need to modify a config file using python. The file has a format similar to
property_one = 0
property_two = 5
i.e there aren't any section names.
Python's configparser module doesn't support sectionless files, but I can use it to load them easily anyway using the trick from here: https://stackoverflow.com/a/26859985/11637934
parser = ConfigParser()
with open("foo.conf") as lines:
lines = chain(("[top]",), lines) # This line does the trick.
parser.read_file(lines)
The problem is, I can't find a clean way to write the parser back to a file without the section header. The best solution I have at the moment is to write the parser to a StringIO
buffer, skip the first line and then write it to a file:
with open('foo.conf', 'w') as config_file, io.StringIO() as buffer:
parser.write(buffer)
buffer.seek(0)
buffer.readline()
shutil.copyfileobj(buffer, config_file)
It works but it's a little ugly and involves creating a second copy of the file in memory. Is there a better or more concise way of achieving this?
Upvotes: 3
Views: 2017
Reputation: 433
Stumbled on a less ugly way of doing this:
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
config_file.write(text)
Upvotes: 3