您当前的位置: 首页 >  Python

FPGA硅农

暂无认证

  • 1浏览

    0关注

    282博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python中配置文件的读取

FPGA硅农 发布时间:2020-11-05 17:43:39 ,浏览量:1

首先在config.ini中写入如下内容

[Mysql-Database]
host=localhost
user=root
password=123456
db=test
charset=utf8

[Email]
host=http://mail.qq.com
address=234567@qq.com
password=123456

然后编写python读取该配置文件,并写入另一配置文件

import configparser

cf = configparser.ConfigParser()
cf.read("F:\\config.ini")  # 读取配置文件,如果写文件的绝对路径,就可以不用os模块

secs = cf.sections()  # 获取文件中所有的section(一个配置文件中可以有多个配置,如数据库相关的配置,邮箱相关的配置,                        每个section由[]包裹,即[section]),并以列表的形式返回
print(secs)

options = cf.options("Mysql-Database")  # 获取某个section名为Mysql-Database所对应的键
print(options)

items = cf.items("Mysql-Database")  # 获取section名为Mysql-Database所对应的全部键值对
Mysqlconfig=dict(items)
print(Mysqlconfig)
print(Mysqlconfig['user'])

host = cf.get("Mysql-Database", "host")  # 获取[Mysql-Database]中host对应的值
print(host)

o=open('F:\\out.ini','w')
cf.write(o)
o.close()

运行结果如下: 在这里插入图片描述 上面是对配置文件的读取和写入,但是有时候,比如图形用户界面,用户在界面上的文本框内输入配置信息,则在计算机中这是一个字符串,python的configparser模块怎么解析它呢,一个简单的方法就是将该字符串写入一个临时文件,然后再用configparser处理,示例如下:

import configparser
import os

def parserConfig(str):
    f=open("tmp.ini","wt",encoding="utf-8")
    f.write(str)
    f.close()
    cf = configparser.ConfigParser()
    cf.read("tmp.ini", encoding="utf-8")
    os.remove("tmp.ini")
    return cf

str='[基本配置]\n\
姓名=Tom\n\
年龄=23\n\
性别=m\n\
学历=硕士\n\
[爱好]\n\
球类=足球\n\
电视=RunningMan\n\
学科=CS\n\
'
#print(str)
cf=parserConfig(str)
print(cf.sections())
print(cf.get("基本配置","姓名"))








关注
打赏
1658642721
查看更多评论
立即登录/注册

微信扫码登录

0.0405s