繁体   English   中英

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

[英]How to remove a section from an ini file using Python 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 +'但它没有用。 我无法截断整个文件,因为它可能有其他不应删除的部分。

您需要使用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.

您最终需要以写入模式打开文件。 这会截断它,但这没关系,因为当你写它时,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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM