600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python读conf配置文件完成登录_python conf配置文件

python读conf配置文件完成登录_python conf配置文件

时间:2021-02-04 10:11:34

相关推荐

python读conf配置文件完成登录_python conf配置文件

#为什么要做配置文件:

#将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不用都去修改代码内部,这个就是我们逐步

#要做的事情,可配置化

#configparser用法

#1)创建configparser对象,并调用read()函数打开配置文件,里面填的参数是地址

#2)配置文件的格式是[]包含的是section,section下有option=value这样的键值对

'''

3.依据section来读取相应的配置数据 读 写

'''

#1.创建configparser对象

import configparser

cf=configparser.ConfigParser()

#2.从配置文件中读取数据

import os

cf.read(os.getcwd()+"/config.conf")

#读取所有section

print(cf.sections()) #返回列表形式 ['mysql_info', 'test_addSection']

#读取section下的option

print(cf.options(section="mysql_info")) #只有key值 ['mysql_host', 'mysql_port', 'mysql_db', 'mysql_user', 'mysql_passwd']

#读取键值对

print(cf.items(section="mysql_info")) #键值对 [('mysql_host', '120.76.42.189'), ('mysql_port', '3306'), ('mysql_db', 'future'), ('mysql_user', 'futurevistor'), ('mysql_passwd', '123456')]

#读section里option

print(cf.get("mysql_info","mysql_db")) #future

print(cf.getint("mysql_info","mysql_port")) #3306

#写

#添加option,修改也用set

cf.set("mysql_info","type","mysql5.7")

#添加section

cf.add_section("test")

cf.set("test","sex","female")

#添加完option section后都要打开文件写入

with open(os.getcwd()+"/config.conf","w") as cfile:

cf.write(cfile) #文件流写到文件中去

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。