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

ult*_*moo 5 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
>>>
Run Code Online (Sandbox Code Playgroud)

似乎remove_section()仅在内存中发生,并且当要求将结果写回ini文件时,没有任何可写的内容。

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

我用来打开文件的模式不正确吗?我尝试使用“ r +”和“ a +”,但没有用。我无法截断整个文件,因为它可能还有其他不应删除的部分。

Bre*_*arn 5

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


fal*_*tru 5

您需要使用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.
Run Code Online (Sandbox Code Playgroud)