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

Question:

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 = ''
Asked By: rohanK0602

||

Answers:

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())
Answered By: ACOG
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.