"""
configparser
配置文件解析模块
配置应用程序的文件
配置信息指的是,程序中有一些数据需要用户自己来指定,不应该固定死,比如qq中开机启动这一个数据
这就需要配置文件
对于配置文件而言,我们的程序最常见的就是读取配置文件操作
当configparser 模块也能修改和创建配置文件 但不常用
"""
import configparser
cfg = configparser.ConfigParser()
cfg.read("my.cfg",encoding="utf-8")
print(cfg.sections()) # 获取所有的分区名字
print(cfg.get("atm","username")) # 获取某个选项的值
print(cfg.get("atm","password")) # 获取某个选项的值
# 所有选项获取的到的都是字符串类型
print(type(cfg.get("atm","password")))
# 提供了 getint getboolean get float 可以直接帮你转换类
print(cfg.getint("atm","age"))
print(type(cfg.getint("atm","age")))
# 判断是否存在分区 或 选项
print(cfg.has_option("atm","age"))
print(cfg.has_section("atm"))
# 获取某个分区下的所有选项
print(cfg.options("atm"))
# 删除分区 和选项
print(cfg.remove_section("car"))
print(cfg.remove_option("atm","sex"))
# 修改或是添加 如果有就修改 没有则添加
cfg.set("atm","age","30")
# 添加分区
cfg.add_section("test")
cfg.set("test","账号","大山炮")
# 写入文件
with open("my.cfg","wt",encoding="utf-8") as f:
cfg.write(f)
import configparser
import os
def login():
if exists_usercfg():
cfg = configparser.ConfigParser()
cfg.read("user.cfg",encoding="utf-8")
user = cfg.get("info","username")
pwd = cfg.get("info","password")
else:
user = input("用户名:")
pwd = input("密码:")
if user == "李大炮" and pwd == "213":
print("登录成功!")
if not exists_usercfg():
res = input("是否记住密码?y/n")
if res == "y":
jzmm(user,pwd)
# 记住密码函数
def jzmm(user,pwd):
cfg = configparser.ConfigParser()
cfg.add_section("info")
cfg.set("info","username",user)
cfg.set("info","password",pwd)
with open("user.cfg","wt",encoding="utf-8") as f:
cfg.write(f)
def exists_usercfg():
if os.path.exists("user.cfg"):
return True
login()