2012-09-09 49 views
0

我正在使用Python模塊iniparse將密鑰保存到INI文件,但我想知道是否有方法使用iniparse從INI文件中刪除密鑰和節。我知道有可能使用ConfigParseriniparse向後兼容ConfigParser,但我無法弄清楚如何使用相同的iniparse對象執行刪除操作。從INI文件中刪除段和鍵使用Python模塊iniparse?

from iniparse import INIConfig, RawConfigParser 

cfg = INIConfig(open('options.ini')) 
print cfg.section.option 
cfg.section.option = 'new option' 

# Maybe I need to use RawConfigParser somehow? 
cfg.remove_option('section','option') 
cfg.remove_section('section') 

f = open('options.ini', 'w') 
print >>f, cfg 
f.close() 

回答

1

要刪除一個部分或一個選項,你只需要刪除它。修改後的代碼如下:

from iniparse import INIConfig 

cfg = INIConfig(open('options.ini')) 
print cfg.section.option 
cfg.section.option = 'new option' 

del cfg.section.option 
del cfg.section 

f = open('options.ini', 'w') 
print >>f, cfg 
f.close() 

注意,如果你想刪除一個整體部分,您不必刪除其選項前:只刪除部分。

還要注意,這樣做的感覺更多Pythonic比使用remove_optionremove_section方法。

+0

@ Petro Romano。這工作。謝謝。我應該意識到我只需要刪除屬性。 – Voltron43

相關問題