如何使用Python ConfigParser从ini文件中删除部分? [英] How to remove a section from an ini file using Python ConfigParser?

查看:451
本文介绍了如何使用Python ConfigParser从ini文件中删除部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python的ConfigParser库从ini文件中删除[section].

I am attempting to remove a [section] from an ini file using Python's ConfigParser library.

>>> 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文件时,没有任何可写的内容.

It appears that the remove_section() happens only in-memory and when asked to write back the results to the ini file, there is nothing to write.

关于如何从ini文件中删除节并将其保留的任何想法吗?

Any ideas on how to remove a section from the ini file and persist it?

我用来打开文件的模式不正确吗? 我尝试使用"r +"& 'a +',它不起作用.我无法截断整个文件,因为它可能还有其他不应删除的部分.

Is the mode that I'm using to open the file incorrect? I tried with 'r+' & 'a+' and it didn't work. I cannot truncate the entire file since it may have other sections that shouldn't be deleted.

推荐答案

您最终需要以写入模式打开文件.这将截断它,但这没关系,因为当您对其进行写入时,ConfigParser对象将写入该对象中仍然存在的所有节.

You need to open the file in write mode eventually. This will truncate it, but that is okay because when you write to it, the ConfigParser object will write all the sections that are still in the object.

您应该做的是打开文件进行读取,读取配置,关闭文件,然后再次打开文件进行写入和写入.像这样:

What you should do is open the file for reading, read the config, close the file, then open the file again for writing and write it. Like this:

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())

这篇关于如何使用Python ConfigParser从ini文件中删除部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆