【问题标题】:How to remove a section from an ini file using Python ConfigParser?如何使用 Python ConfigParser 从 ini 文件中删除部分?
【发布时间】:2016-09-12 22:47:17
【问题描述】:

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

【问题讨论】:

    标签: python ini configparser


    【解决方案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())
    

    【讨论】:

    • 谢谢,这行得通。它确实消除了 cmets 等文件,因为 ConfigParser 不解析这些文件。是否有推荐用于 ini 解析的功能更强大的 Python 库?
    • @ultimoo:快速谷歌建议ConfigObj。我自己没用过。您必须检查一下它是否满足您的需求。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 2012-09-02
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      相关资源
      最近更新 更多