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

此页面是否是列表页或首页?未找到合适正文内容。

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

标签:preoptionitemspythoini函数igpntaons

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 格式的文件Writean.ini-formatrepresentationoftheconfigurationstate.
  • -add_section(section)添加一个新的section
  • -set( section, option, value 对section中的option进行设置,需要调用write将内容写入配置文件
  • -remove_section(section)删除某个 section
  • -remove_option(section, option)

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

标签:preoptionitemspythoini函数igpntaons

原文地址:http://www.cnblogs.com/zy516563199/p/7644664.html

作者: liuzhihao

为您推荐

返回顶部