configparser模块

本文介绍了Python的configparser模块,用于处理配置文件。主要内容包括读取配置文件、获取选项值、判断选项是否存在、修改和删除配置项,以及写入配置文件。示例代码展示了如何读取、修改和保存配置信息,以及检查配置文件是否存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

"""
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()
 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值