簡體   English   中英

"用Python3讀寫配置文件,不丟失文件中的注釋"

[英]Read and write a config file with Python3 without losing the comments in the file

我想讀取具有注釋行的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM