wildfire
wildfire

Reputation: 119

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

Upvotes: 2

Views: 6180

Answers (3)

Jemoba
Jemoba

Reputation: 11

config = configparser.ConfigParser()

should be

config = configparser.RawConfigParser()

everything else works perfectly

Upvotes: 0

guichao
guichao

Reputation: 198

import os
import ConfigParser  # spelling mistake, 

config = ConfigParser.ConfigParser()  # need create an object first

#directory of folder
testdir = os.path.dirname(os.path.realpath(__file__))
#file directory
newdir = os.path.join(testdir,"test99.ini") # use os.path.join to concat filepath.

#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

Upvotes: 1

Souradeep Nanda
Souradeep Nanda

Reputation: 3288

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)

Upvotes: 2

Related Questions