Search code examples
pythonconfigparser

How to add section and values to ini using configparser in Python?


I would like to ask why the ini file created using my code is empty. I intend to create an ini file on the same directory as that of the py file. So far, the ini is generated but it is empty.

import os
import configparser

config = configparser.ConfigParser

#directory of folder
testdir = os.path.dirname(os.path.realpath(__file__))
#file directory
newdir = testdir + "\\test99.ini"

#config ini
config.add_section('testdata')
config.add_section('testdata2')
config.set('testdata','val', '200')
config.set('testdata2','val', '300')

#write ini
newini = open(newdir, 'w')
config.write(newini)
newini.close

Solution

  • You are missing some parenthesis and importing the wrong things. Consult documentation.

    import os
    import configparser
    
    config = configparser.RawConfigParser()
    
    #directory of folder
    testdir = os.path.dirname(os.path.realpath(__file__))
    #file directory
    newdir = testdir + "/test.ini"
    
    #config ini
    config.add_section('testdata')
    config.add_section('testdata2')
    config.set('testdata','val', '200')
    config.set('testdata2','val', '300')
    
    #write ini
    with open(newdir, 'w') as newini:
        config.write(newini)