python3读写配置文件

配置文件conf.ini
[token]
ryst = 46ca47ffbb06ebea09f8b9d812d1a7d3

写配置

    import configparser
    # 获取token写入配置文件
    base_dir = str(os.path.dirname(os.path.dirname(__file__)))
    base_dir = base_dir.replace('\\', '/')
    file_path = base_dir + "/config/conf.ini"
    print(file_path)
    # 写token
    config = configparser.ConfigParser()
    config.add_section("token")
    config.set('token', 'RYST', RYST)
    with open(file_path, 'w')as conf:
        config.write(conf)

读配置

import configparser

base_dir = str(os.path.dirname(os.path.dirname(__file__)))
base_dir = base_dir.replace('\\', '/')
file_path = base_dir + "./config/conf.ini"

cf = configparser.ConfigParser()   # configparser类来读取config文件
cf.read(file_path)

RYST = cf.get("token", "RYST")
# print(RYST)
host = cf.get("mysqlconf", "host")
port = cf.get("mysqlconf", "port")
db = cf.get("mysqlconf", "db_name")
user = cf.get("mysqlconf", "user")
password = cf.get("mysqlconf", "password")

猜你喜欢

转载自blog.csdn.net/ezreal_tao/article/details/84840679