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
wildfire
  • 119
  • 2
  • 4
  • 9

3 Answers3

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)
Souradeep Nanda
  • 3,116
  • 2
  • 30
  • 44
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
guichao
  • 198
  • 1
  • 7
  • I cannot find the ConfigParser. It seems the problem is due to a missing parenthesis when creating an object. – wildfire Mar 02 '18 at 03:57
0
config = configparser.ConfigParser()

should be

config = configparser.RawConfigParser()

everything else works perfectly

Jemoba
  • 11
  • 2