Change configuration file by configparser remove_section

Asked

Viewed 109 times

2

How to save the configuration file (.ini) after deleting an option or section?

I’m doing it this way:

test ini.

[LOCAL]
url = 'http://localhost:8080/'
username = 'usuario'
password = 'SECRET'

[TESTE]
url = 'http://localhost:8080/teste/'
username = 'usuario'
password = 'SECRET'

removes.py

import configparser

parser = configparser.ConfigParser()
parser.read('teste.ini')

print('Lendo Valores:')
for section in parser.sections():
    print(section)
    for name, value in parser.items(section):
        print(f"{name} = {value}")

parser.remove_option('LOCAL', 'password')
parser.remove_section('TESTE')

print('\Valor Modificado:')
for section in parser.sections():
    print(section)
    for name, value in parser.items(section):
        print(f"{name} = {value}")

However I can’t save the change, in the tests I did using some examples I found on the internet the file duplicates some TAGS, saves only half the file and sometimes even saves.

1 answer

1


I continued with the tests here and ended up mixing some examples I found on the internet, so I managed to solve the problem, I do not know if it was the best way to solve the problem.

import configparser

parser = configparser.ConfigParser()
parser.read("teste.ini")

print('Lendo Valores:')
for section in parser.sections():
    print(section)
    for name, value in parser.items(section):
        print(f"{name} = {value}")

parser.remove_option('TESTE', 'password')
parser.remove_section('LOCAL')

with open("teste.ini", "w") as ArqTeste:
  parser.write(ArqTeste)
ArqTeste.close()

print('Valor Modificado:')
for section in parser.sections():
    print(section)
    for name, value in parser.items(section):
        print(f"{name} = {value}")

As I said earlier, I don’t know if it was the best way, but it was the way I was able to solve my problem and continue the development...

  • 1

    Just one detail, you don’t need to run ArqTeste.close() for the with already does it for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.