-
Notifications
You must be signed in to change notification settings - Fork 82
Description
When ConfigObj parses a file with inline comments, it stores those comments with the leading # character. When ConfigObj later writes back to the file, the whitespace between the value and the # character is lost changing lines like
key = value # my comment
to
key = value# my comment
Steps to reproduce
Create a test.ini file like this
[section1]
key = value # my commentThen execute this code
from configobj import ConfigObj
config = ConfigObj('test.ini')
config.write()Expected result
That the test.ini file would remain unchanged
Actual result
test.ini now contains
[section1]
key = value# my commentWorkaround
Given that ConfigObj will add in an inline comment with the whitespace if the stored inline comment doesn't contain the # character
configobj/src/configobj/__init__.py
Lines 2001 to 2002 in c89a025
| if not comment.startswith('#'): | |
| start += self._a_to_u(' # ') |
here's a workaround to ensure inline comments have the leading space before the # character. This is done by removing the # character from the stored inline comment.
import re
pattern = re.compile(r'^#\s*')
for section in config.sections:
for key, inline_comment in config[section].inline_comments.items():
if inline_comment is not None:
config[section].inline_comments[key] = pattern.sub('', inline_comment)