使用configparser 读 or 写 配置文件ini

config.ini文件

[config]
username = 2024222222
password = 123456
time = 202320241
num1 = 1
id1 = 018819
num2 = 1
id_1 = 018818

读取配置文件

def read_ini():
    file = 'config.ini'
    con = configparser.ConfigParser()
    con.read(file, encoding='utf-8')
    item = con.items('config')
    item = dict(item)
    print(item)
    semester = item['time']  # 获取配置文件中的学期
    print(semester)

写入配置文件

def write_ini():
    file = 'config.ini'
    con = configparser.ConfigParser()
    con.read(file, encoding='utf-8')
    con.set('config', 'username', '111111111111111111111111111')
    con.set('config', 'password', '123456465')
    with open(file, 'w') as f:
        con.write(f)

username 与 password 对应的值已改变

其它

也可以用json或者yaml

posted @ 2024-11-10 10:32  __username  阅读(7)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。