如何使用 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+' 但它没有用。我无法截断整个文件,因为它可能有其他不应删除的部分。
您最终需要以写入模式打开文件。这将截断它,但这没关系,因为当您写入它时,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())
您需要使用 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.
我正在尝试使用 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+' 但它没有用。我无法截断整个文件,因为它可能有其他不应删除的部分。
您最终需要以写入模式打开文件。这将截断它,但这没关系,因为当您写入它时,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())
您需要使用 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.