ini文件处理
get,getint,set
import configparser
cfg = configparser.ConfigParser()
read_ok=cfg.read('E:/test/mysql.ini') #操作之前必须先 read到内存中
print(read_ok)
print(cfg.sections())
print(cfg.default_section)
print(cfg._sections)
for k,v in cfg.items('mysqld'):
print(k,v)
x = cfg.get('mysqld','a')
print(x,type(x))
y = cfg.getint('mysqld','port')
print(y,type(y))
cfg.set('mysqld','c','True')
x = cfg.get('mysqld','c')
print(x,type(x))
read(filenames, encoding=None)
尝试读取和解析文件名列表,返回已成功解析的文件名列表。如果文件名是字符串,则将其视为单个文件名。如果无法打开文件名中命名的文件,该文件将被忽略。这是为了能够指定潜在的配置文件位置列表(例如,当前目录,用户的主目录和一些系统范围的目录),并且将读取列表中的所有现有配置文件。
写入配置文件
把所有配置项读取到内存中,用内存数据结构,进行读写操作,并不持久化.需要自行写入文件
with open('E:/test/test.ini','w') as f:
cfg.write(f)
字典结构,可当做字典操作
print(cfg['mysqld']['port'])
print(type(cfg['mysqld']['port']))
添加section
cfg.add_section('test')
with open('E:/test/test.ini','w') as f:
cfg.write(f)
删除section
if cfg.has_section('test'):
cfg.remove_section('test')
with open('E:/test/test3.ini','w') as f:
cfg.write(f)
字典方式添加section
cfg['test3'] = {}
cfg['test3']['test'] = '123'
with open('E:/test/test3.ini','w') as f:
cfg.write(f)
删除option
if cfg.has_option('test3','test'):
cfg.remove_option('test3','test')
with open('E:/test/test3.ini','w') as f:
cfg.write(f)
in
print('test' in cfg['test3'])