python3 configparser 操作配置文件

随意

configparser 其实就是读取文件成字典,然后操作字典后重写文件。
存在问题:
1、 大小写问题
2、其他说明注释

import configparser


client = configparser.ConfigParser()
file_client = './client.cnf'

# 读取配置文件成字典列表,读出来的都是小写
client.read(file_client, encoding='utf-8')
# client_section = client.sections()

if not client.has_section('client'):
    print('没有client 这个字段,干不了阿')
    exit()


if not client.has_option('client', 'default-character-set'):
    print('没有这一行得添加!')
    # print('NOT OK 2')1.py:17
    client.set('client', 'default-character-set', 'utf8')

if "utf8" != client.get('client', 'default-character-set'):
    print('原来的值为:', client.get('client', 'default-character-set'))
    client.set('client', 'default-character-set', 'utf8')
    print('修改了为utf8')

items = client.items('client')
for i,j in items:
    print(i+'='+j)
# 把字典写回去,源文件中注释和大小写都错了
client.write(open(file_client, 'w'))
posted @ 2020-06-13 17:16  zhaomy-test  阅读(200)  评论(0)    收藏  举报