PythonStudy——configparser 模块

"""
    configparser模块
    是什么:
        用于解析配置文件的模块

    配置文件的定义:
        用于编写保存某个软件或是某个系统的 一系列参数的文件
        设置 参数
        为什么需要配置文件
        无论是什么样软件应用程序  在执行的过程中 都需要很多的参数
        而一些参数经常会需要修改
        例如: qq里面的下载路径  ATM中的错误次数
        如果直接写死在程序中,使用者在需要修改参数时 就不得不直接修改源代码
        这是非常不合理的,所以我们通常还会吧这些需要变化的参数 放到配置文件中

"""

# 打开配置文件来读取参数
# with open("atm.cfg","rt") as f:
#     err_count = int(f.read())
# err_count = 0

import configparser
# 创建 解析对象
c = configparser.ConfigParser()
c.read("atm.cfg",encoding="utf-8") # 读取指定的配置文件

# 获取一个配置项
count = int(c.get("atm","err_count"))
print(int(count))


# print(type(count))








temp_count = 0
while True:
    if temp_count >= count:
        print("该账户以及被锁定!")
        break
    name = input("useranme:")
    pwd = input("password:")
    if name == "jerry" and pwd == "123":
        print("登录成功!")
        break
    else:
        print("用户名或密码不正确!")
        temp_count += 1



"""
configparser 用来解析配置文件的
对配置文件有各式要求
    只能由分区和选项
    section 和 option
    同一个section' 不能有重复的option
    不能有重复的section
    不区分数据类型 都是字符串
    # 可以用来注释
    任何option都必须包含在section

需要掌握的方法
read(文件路径,编码)
get(分区名称,选项名称) 返回的是字符串
getint getfloat getboolean  

练习 记住密码的功能
用配置文件记录用户名和密码 如果说配置文件中存在用户名和密码则直接读取并登陆成功!
否则用户输入用户名密码 登录成功时 写入配置文件

    
"""




import configparser

c = configparser.ConfigParser()
c.read("atm.cfg",encoding="utf-8")

# 获取所有分区名称
print(c.sections())
# 某个分区下所有option名字
print(c.options("atm"))

# 封装了类型转换的方法
# count = c.getint("atm","err_count")
# c.getfloat()
# c.getboolean()



# c.set("atm","test","123")# 设置某个选项的值 如果option以及存在则覆盖
# c.add_section("atm1") # 添加一个新分区
# c.set("atm1","test","123")

print(list(c.keys()))
# print(list(c.values())[1].name)
print(list(c.values()))
# dir 可以查看 某个对象所有可用的属性  __开头不要管 系统自带的
print(dir(list(c.values())[1]))


# 写入数据到文件
with open("atm.cfg","wt",encoding="utf-8") as f:
    c.write(f)


"代码生成配置文件"
"了解   一般用户来写 程序来读"

import configparser
c = configparser.ConfigParser()

c.add_section("test")
c.set("test","name","jack")

with open("test.cfg","wt",encoding="utf-8") as f:
    c.write(f)

原文地址:https://www.cnblogs.com/tingguoguoyo/p/10896516.html