V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fmdxx1991
V2EX  ›  Python

用 configparser 更新配置项的时候怎么保留注释啊?

  •  
  •   fmdxx1991 · 2021-05-27 08:06:24 +08:00 · 1878 次点击
    这是一个创建于 1037 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一写入配置文件里的注释就全没了,影响可读性,百度了下,看解决办法要修改模块源码,有没有更好的办法啊?
    5 条回复    2021-05-27 15:35:26 +08:00
    Vinty
        1
    Vinty  
       2021-05-27 09:07:05 +08:00
    很简单,修改前缀不要把它标记为注释读取就行

    ```
    config.ini
    [default_settings]
    ; comment
    value = 1
    ```

    ```python
    from configparser import ConfigParser
    conf = ConfigParser(comment_prefixes='/', allow_no_value=True)
    conf.read("config.ini")
    with open("new_config.ini", "w") as fp:
    conf.write(fp)
    ```
    fmdxx1991
        2
    fmdxx1991  
    OP
       2021-05-27 10:28:59 +08:00
    @Vinty 有点问题哎,
    ```
    config.ini
    [default_settings]
    ; comment
    ;value = 1
    #value=2
    value=3
    ```
    注释是这个样子的,然后就报错了=。。=( option ';value' in section 'default_settings' already exists ),配置文件开头也有注释,运行的话也是直接报错
    fmdxx1991
        3
    fmdxx1991  
    OP
       2021-05-27 10:44:54 +08:00
    @fmdxx1991
    [default_settings]
    ; comment
    #value = 1
    #value = 2
    value=3
    这样的,前面写错了
    xingheng
        4
    xingheng  
       2021-05-27 13:02:11 +08:00
    换 yaml
    Vinty
        5
    Vinty  
       2021-05-27 15:35:26 +08:00
    #2 因为 read 的时候就已经丢掉了注释,所以为了保存注释,这里把注释的前缀修改成了另一个字符`\`,然后把注释当作一条字段读取了进来,
    你这里#value = 1, #value = 2 就是一个重复的字段了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4521 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 10:01 · PVG 18:01 · LAX 03:01 · JFK 06:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.