Python学习笔记21(读取配置文件)

1、基本的读取操作

  • -read(filename)               直接读取文件内容
  • -sections()                      得到所有的section,并以列表的形式返回
  • -options(section)            得到该section的所有option
  • -items(section)                得到该section的所有键值对
  • -get(section,option)        得到section中option的值,返回为string类型
  • -getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
#peizhi.ini

[section1111]
name = zy
age = 23

[section2222]
ip = 192.168.1.1
port = 8080
import configparser   #引入必要的包

cf = configparser.ConfigParser()  #实例化configparser对象
cf.read("peizhi.ini")       #读取配置文件

s = cf.sections()   #读取所有的section
i = cf.items('section2222') #读取该section下所有的键值对
o = cf.options('section2222') #读取该section下的所有option,即键
k = cf.get('section2222','ip') #得到section中该option的值
has_sec = cf.has_option('section2222','name') #判断该键值对是否存在

2、基本的写操作

  • -write(fp)  将config对象写入至某个 .init 格式的文件  Write an .ini-format representation of the configuration state.
  • -add_section(section)   添加一个新的section
  • -set( section, option, value   对section中的option进行设置,需要调用write将内容写入配置文件
  • -remove_section(section)  删除某个 section
  • -remove_option(section, option) 
posted @ 2017-10-10 11:22  爱锁屏  阅读(176)  评论(0编辑  收藏  举报