2

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

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1
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

1 Comment

I cannot find the ConfigParser. It seems the problem is due to a missing parenthesis when creating an object.
0
config = configparser.ConfigParser()

should be

config = configparser.RawConfigParser()

everything else works perfectly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.