简体   繁体   中英

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

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)
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
config = configparser.ConfigParser()

should be

config = configparser.RawConfigParser()

everything else works perfectly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM