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

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

Using configparser to remove section name only but retain its key and value pairs

问题

我试图从INI文件中删除该部分,但我希望保留该部分的键和值。

我尝试这样删除一个部分:

  1. with open('testing.ini', "r") as configfile:
  2. parser.read_file(configfile)
  3. print(parser.sections())
  4. parser.remove_section('top')
  5. print(parser.sections())
  6. with open('testing.ini', "w") as f:
  7. parser.write(f)

我生成一个INI文件如下:

  1. [top]
  2. username = 'rk'
  3. pass = ''

INI文件的预期结果:

  1. username = 'rk'
  2. 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

  1. with open('testing.ini', "r") as configfile:
  2. parser.read_file(configfile)
  3. print(parser.sections())
  4. parser.remove_section('top')
  5. print(parser.sections())
  6. with open('testing.ini', "w") as f:
  7. parser.write(f)

I m generating a ini file like this

  1. [top]
  2. username = 'rk'
  3. pass = ''

expected Result of ini file

  1. username = 'rk'
  2. pass = ''

答案1

得分: 0

configparser通常不会在没有节的情况下运行,但您可以通过在从配置中删除部分之前手动添加部分项来构建一个解决方法。

  1. with open('testing.ini', 'r') as configfile:
  2. parser.read_file(configfile)
  3. print(parser.sections())
  4. text = '\n'.join(['='.join(item) for item in parser.items('top')])
  5. with open('testing.ini', 'w') as config_file:
  6. config_file.write(text)
  7. parser.remove_section('top')
  8. 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

  1. with open('testing.ini', "r") as configfile:
  2. parser.read_file(configfile)
  3. print(parser.sections())
  4. text = '\n'.join(['='.join(item) for item in parser.items('top')])
  5. with open('testing.ini', 'w') as config_file:
  6. config_file.write(text)
  7. parser.remove_section('top')
  8. 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:

确定