2011-07-08 17 views
22

如何在部分內給給定文件寫評註?用ConfigParser給文件寫評論

如果我有:

import ConfigParser 
with open('./config.ini', 'w') as f: 
    conf = ConfigParser.ConfigParser() 
    conf.set('DEFAULT', 'test', 1) 
    conf.write(f) 

我會得到的文件:

[DEFAULT] 
test = 1 

但我怎麼能得到與批註的文件裏面[DEFAULT]部分,如:

[DEFAULT] 
; test comment 
test = 1 

我知道我可以通過下面的代碼寫文件:

import ConfigParser 
with open('./config.ini', 'w') as f: 
    conf = ConfigParser.ConfigParser() 
    conf.set('DEFAULT', 'test', 1) 
    conf.write(f) 
    f.write('; test comment') # but this gets printed after the section key-value pairs 

這是ConfigParser的可能嗎?我不想嘗試另一個模塊,因爲我需要儘可能將我的程序保存爲「庫存」。

+0

考慮ConfigParser寫的配置文件後,我決定使用舊的標準文件寫我的文件接口'f = open('test.ini','w'); f.write('blabla')'因爲ConfigParser模塊甚至沒有以預先定義的順序寫入(因爲它使用字典,即使其中一個例子說明寫入是按照某種順序進行的:[python docs] (http://docs.python.org/library/configparser.html#examples)) – razvanc

+0

如果你還在身邊,我會建議你寫一個簡短的回答,並將其標記爲已接受。即使在發表評論之後,我也閱讀了建議的答案,並得出了相同的結論......但是花了我一段時間,我甚至已經投票選出了您選擇的解決方案...... – estani

回答

19

可以使用allow_no_value選項,如果你有V版爲> = 2.7

這個片斷:

import ConfigParser 

config = ConfigParser.ConfigParser(allow_no_value=True) 
config.add_section('default_settings') 
config.set('default_settings', '; comment here') 
config.set('default_settings', 'test', 1) 
with open('config.ini', 'w') as fp: 
    config.write(fp) 


config = ConfigParser.ConfigParser(allow_no_value=True) 
config.read('config.ini') 
print config.items('default_settings') 

將創建一個ini文件是這樣的:

+0

作爲一個側面說明,只要你不想在'DEFAULT'部分寫註釋,就會工作 - 在寫函數中有一個檢查來避免寫'= None',但是隻有當不寫出'默認'部分。 –

+0

好點。幸運的是,在Python 3.6中,'configparser'模塊沒有這種奇怪的行爲。因此,'config = configparser。ConfigParser({「; comment」:None},allow_no_value = True)'在缺省部分插入註釋,不帶任何'= None'結尾。爲了保證輸出的正確排序,需要'collections.OrderedDict'(而不是像我的例子中的'dict')。 – EOL

+0

此選項僅適用於您創建新文件的情況。如果你正在編輯一個帶有註釋的文件,它們將全部清除:/ – GEPD

3

您可以創建以#或開頭的變量。性格:

conf.set('default_settings', '; comment here', '') 
conf.set('default_settings', 'test', 1) 

創建的conf文件

[default_settings] 
    ; comment here = 
    test = 1 

ConfigParser.read功能將無法解析第一個值

config = ConfigParser.ConfigParser() 
config.read('config.ini') 
print config.items('default_settings') 

[('test','1')] 
+1

與後面的= =相當醜陋。 – ThiefMaster

+0

也許這是ConfigParser最好的唯一方法。謝謝 – razvanc

+0

你可以去掉尾隨的'='。當你想寫一個註釋時,你只需在調用'set'方法時省略第三個參數。否則,您將爲其分配一個空字符串,導致不需要的尾部「=」。 – benregn