1.介绍
该模块主要用来操作及设置配置文件, 可以以键值对的形式存放信息.
例如:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
2.使用:
import configparser
conf = configparser.ConfigParser() # 生成一个configparser对象
conf.read('user_info.conf', encoding='utf-8') # 读取文件
print(conf.sections()) # 打印section
conf['shit1'] = {} # 新增一个section
conf['shit1']['love'] = 'string'
conf.add_section('happy') # 另一种新增方法
conf.add_section('happy1')
conf.remove_option('shit1', 'love') # 删除option
conf.remove_section('happy1') # 删除section
with open('user_info.conf', 'w+') as f:
conf.write(f) # 写入文件
#result
['bitbucket.org', 'topsecret.server.com', 'shit1', 'happy', 'happy1']
使用二:
import configparser
conf = configparser.ConfigParser()
conf.read('test.txt', encoding='utf-8')
print(conf.sections())
print(conf.options('topsecret.server.com'))
print(conf.items('topsecret.server.com'))
print(conf.values())
print(conf.get('topsecret.server.com', 'Port'))
conf['DEFAULT']['shot'] = '123'
conf.add_section('happy')
conf.add_section('happy2')
conf.set('happy', 'shot', '456')
conf.remove_option('DEFAULT', 'shot')
conf.remove_section('happy2')
conf.write(open('test.txt', 'w'))
# result
['bitbucket.org', 'topsecret.server.com']
['port', 'forwardx11', 'serveraliveinterval', 'compression', 'compressionlevel', 'shot']
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'no'), ('shot', '123'), ('port', '50022')]
ValuesView(<configparser.ConfigParser object at 0x00000169507E27B8>)
50022