2016-05-17 105 views
3

我正在嘗試使用Python的ConfigParser庫從ini文件中刪除[section]。如何使用Python ConfigParser從ini文件中刪除一個節?

>>> import os 
>>> import ConfigParser 
>>> os.system("cat a.ini") 
[a] 
b = c 

0 

>>> p = ConfigParser.SafeConfigParser() 
>>> s = open('a.ini', 'r+') 
>>> p.readfp(s) 
>>> p.sections() 
['a'] 
>>> p.remove_section('a') 
True 
>>> p.sections() 
[] 
>>> p.write(s) 
>>> s.close() 
>>> os.system("cat a.ini") 
[a] 
b = c 

0 
>>> 

看來,remove_section()只發生在內存中,當要求寫回結果的ini文件,沒有什麼可寫的。

有關如何從ini文件中刪除一部分並堅持它的任何想法?

我用來打開文件的模式不正確嗎? 我用'r +'&'a +'嘗試過,但沒有奏效。我不能截斷整個文件,因爲它可能有其他部分不應該被刪除。

回答

1

您需要最終以寫入模式打開文件。這將截斷它,但這是好的,因爲當你寫入它時,ConfigParser對象將寫入仍然在對象中的所有部分。

你應該做的是打開文件閱讀,閱讀配置,關閉文件,然後再次打開文件寫入和寫入。像這樣:

with open("test.ini", "r") as f: 
    p.readfp(f) 

print(p.sections()) 
p.remove_section('a') 
print(p.sections()) 

with open("test.ini", "w") as f: 
    p.write(f) 

# this just verifies that [b] section is still there 
with open("test.ini", "r") as f: 
    print(f.read()) 
+0

謝謝,這工作。它刪除了註釋文件等,因爲ConfigParser不解析這些文件。是否有更多功能豐富的Python庫推薦用於ini解析? – ultimoo

+0

@ultimoo:快速谷歌建議[ConfigObj](https://pypi.python.org/pypi/configobj/5.0.6)。我自己並沒有使用它。你必須檢查它是否滿足你的需求。 – BrenBarn

3

您需要使用file.seek更改文件位置。否則,p.write(s)在文件末尾寫入空字符串(因爲配置在remove_section後爲空)。

而您需要撥打file.truncate,以便清除當前文件位置後的內容。

p = ConfigParser.SafeConfigParser() 
with open('a.ini', 'r+') as s: 
    p.readfp(s) # File position changed (it's at the end of the file) 
    p.remove_section('a') 
    s.seek(0) # <-- Change the file position to the beginning of the file 
    p.write(s) 
    s.truncate() # <-- Truncate remaining content after the written position. 
相關問題