代码之家  ›  专栏  ›  技术社区  ›  buhtz

使用Python3读取和写入配置文件,而不会丢失文件中的注释

  •  0
  • buhtz  · 技术社区  · 8 年前

    我想读取具有注释行的INI格式的配置文件。我不想在应用程序将配置写回文件时丢失这些行。

    我该怎么做?

    Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23) 
    [GCC 7.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import configparser
    >>> cfg = configparser.ConfigParser()
    >>> cfg.read_string('''[DEFAULT]
    ... # comment
    ... parameter = 7''')
    >>> f = open('my.conf', 'w')
    >>> cfg.write(f)
    >>> f.close()
    >>> 
    $ cat my.conf
    [DEFAULT]
    parameter = 7
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   buhtz    4 年前

    这个 ConfigObj 是解决方案。