英文:
Using configparser to remove section name only but retain its key and value pairs
问题
我试图从INI文件中删除该部分,但我希望保留该部分的键和值。
我尝试这样删除一个部分:
with open('testing.ini', "r") as configfile:
parser.read_file(configfile)
print(parser.sections())
parser.remove_section('top')
print(parser.sections())
with open('testing.ini', "w") as f:
parser.write(f)
我生成一个INI文件如下:
[top]
username = 'rk'
pass = ''
INI文件的预期结果:
username = 'rk'
pass = ''
英文:
I am trying to remove the section from ini file but i want to retain that section's keys and values.
I tried to remove a section like this
with open('testing.ini', "r") as configfile:
parser.read_file(configfile)
print(parser.sections())
parser.remove_section('top')
print(parser.sections())
with open('testing.ini', "w") as f:
parser.write(f)
I m generating a ini file like this
[top]
username = 'rk'
pass = ''
expected Result of ini file
username = 'rk'
pass = ''
答案1
得分: 0
configparser通常不会在没有节的情况下运行,但您可以通过在从配置中删除部分之前手动添加部分项来构建一个解决方法。
with open('testing.ini', 'r') as configfile:
parser.read_file(configfile)
print(parser.sections())
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('testing.ini', 'w') as config_file:
config_file.write(text)
parser.remove_section('top')
print(parser.sections())
英文:
configparser generally does not operate without sections, but you could construct a workaround by manually adding the section items into the config before removing the section altogether
with open('testing.ini', "r") as configfile:
parser.read_file(configfile)
print(parser.sections())
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('testing.ini', 'w') as config_file:
config_file.write(text)
parser.remove_section('top')
print(parser.sections())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论