Skip to content

Writing inline comments to a file removes the whitespace between the value and the comment #261

@gene1wood

Description

@gene1wood

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 comment

Then 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 comment

Workaround

Given that ConfigObj will add in an inline comment with the whitespace if the stored inline comment doesn't contain the # character

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions