如何使用Python ConfigParser从ini文件中删除节?

2024-05-02 18:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用Python的ConfigParser库从ini文件中删除一个[section]。

>>> 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+”但没用。我无法截断整个文件,因为它可能有其他不应删除的部分。


Tags: 文件importtrueossectionopensystemini