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

时间:2016-05-17 01:54:38

标签: python ini configparser

我正在尝试使用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 +'并且它不起作用。我无法截断整个文件,因为它可能有其他部分不应删除。

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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())