Code
[ url]
baidu = http: // www. baidu. com
[ value]
send_value = 百度
[ server]
ip = 220.181 .111 .188
封装的格式可以套用
import configparser
class ReadConfigIni ( ) :
def __init__ ( self, filename) :
self. cf = configparser. ConfigParser( )
self. cf. read( filename)
def getConfigValue ( self, section, name) :
value = self. cf. get( section, name)
return value
DoConfigIni = ReadConfigIni( "test.ini" )
BaiUrl = DoConfigIni. getConfigValue( "url" , "baidu" )
print ( "通过函数getConfigValue获得的值:" , BaiUrl)
cf.ini文件
[ db]
db_host = 127.0 .0 .1
db_port = 80
db_user = root
db_pass = root
host_port = 69
[ concurrent]
thread = 10
processor = 20
kong =
op_cf.py文件
ini文件的增删查找演示
操作完成后都要加上 config.write(open(“cf.ini”,“w”)) (易错点)
import configparser
config = configparser. ConfigParser( )
config. read( "cf.ini" , encoding= "utf-8" )
print ( config. sections( ) )
print ( config. options( "db" ) )
print ( config. get( "db" , "db_host" ) )
print ( config. get( "concurrent" , "processor" ) )
print ( config. get( "concurrent" , "kong" ) )
print ( config. items( "db" ) )
config. set ( "db" , "db_port" , "80" )
config. write( open ( "cf.ini" , "w" ) )
print ( config. get( "db" , "db_port" ) )
print ( config. has_option( "concurrent" , "thread" ) )
print ( config. has_option( "concurrent" , "aa" ) )
print ( config. has_option( "concurrent" , "kong" ) )
print ( config. has_section( "db" ) )
print ( config. has_section( "1b" ) )
if not config. has_section( "default" ) :
config. add_section( "default" )
if not config. has_option( "default" , "db_host" ) :
config. set ( "default" , "db_host" , "1.1.1.1" )
config. write( open ( "cf.ini" , "w" ) )
print ( config. items( "default" ) )
config. remove_section( "default" )
config. write( open ( "cf.ini" , "w" ) )
print ( config. sections( ) )