使用configparser删除部分名称,但保留其键和值对。

huangapple go评论57阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月6日 22:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定