〇:配置文件管理模块:
help(configparser.ConfigParser)
| dir(conf)
|
一 写入一个配置文件:
import configparser # 写入一个配置文件 # 得到一个configparser对象 conf=configparser.ConfigParser() conf["TOM"]={ "age":20, "like":"gril" } conf['Lili']={ "age":30, "like":"man" } with open("people.ini","w")as f:
conf.write(f) |
二:读取并修改配置文件
|
In [28]: help(conf.sections) Help on method sections in module configparser:
sections() method of configparser.ConfigParser instance Return a list of section names, excluding [DEFAULT] In [29]: help(conf.read) Help on method read in module configparser:
read(filenames, encoding=None) method of configparser.ConfigParser instance Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the list will be read. A single filename may also be given.
Return list of successfully read files.
|
获取值,不存在的时候会报错 | In [50]: conf.get('DEFAULT','compression') Out[50]: 'yes' | |
判断是否是布尔类型,不是布尔类型时候报错 | In [56]: conf.getboolean('DEFAULT','forwardx11') Out[56]: True | |
has_option | 判断有没有这个 option | In [63]: conf.has_option(conf.default_section,"sadf") Out[63]: False |
has_section | 判断有没有这个 section | |
clear | 清空sections 只会清空非'DEFAULT' | In [67]: conf.clear() In [68]: conf.sections() Out[68]: [] |
Iteams | 类似于dick中的 Iteams用法 | In [82]: it=conf.items() In [83]: for key,value in it: ...: print(key,value) ...: DEFAULT <Section: DEFAULT> bitbucket.org <Section: bitbucket.org> topsecret.server.com <Section: topsecret.server.com> TOM <Section: TOM> Lili <Section: Lili> |
keys | In [86]: for i in conf.keys(): ...: print(i) ...: DEFAULT bitbucket.org topsecret.server.com TOM Lili | |
options | 需要传入一个值 这个值是section的值, 字符串类型 | In [104]: conf.options('bitbucket.org') Out[104]: ['user', 'compression', 'compressionlevel', 'serveraliveinterval', 'forwardx11'] |
sections | 获得sections | In [107]: conf.sections() Out[107]: ['bitbucket.org', 'topsecret.server.com', 'TOM', 'Lili'] |