通过python读取ini配置文件

作者: 测试帮日记 | 来源:发表于2017-10-19 09:15 被阅读118次

转发+点赞=支持

ini是啥

你可以理解为就是一个配置文件的统称吧。比如test.conf,这样的你可以理解为他就是ini文件,里面一般存放一些配置信息。比如数据库的基本信息,一会我们进行讲解!

那么ta的好处是啥呢?就是把一些配置信息提出去来进行单独管理,如果以后有变动只需改配置文件,无需修改代码。

ini中的基本格式

[名称,根据实际情况写就行,没啥讲究]

key1=value1

key2=value2

python中通过ConfigParser模块来进行读取操作

实战

演示场景:

1、创建一个数据库配置文件,名字为db.conf,内容如下:

[DATABASE]

host = 127.0.0.1

port = 3306

user = root

passwd = vertrigo

db = testdb

charset = utf8

2、在python中读取信息并连接数据库,代码如下:

import configparser

import mysql.connector

class GetDB:

def __init__(self, db_config):

config = configparser.ConfigParser()

config.read(db_config)

#把配置文件里的数据读取出来并保存

self.host = config['DATABASE']['host']

self.port = config['DATABASE']['port']

self.user = config['DATABASE']['user']

self.passwd = config['DATABASE']['passwd']

self.db = config['DATABASE']['db']

self.charset = config['DATABASE']['charset']

#这里就是链接数据库了

def get_conn(self):

try:

conn = mysql.connector.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db, charset=self.charset)

return conn

except Exception as e:

print('%s', e)

sys.exit()

相关文章

  • 通过python读取ini配置文件

    转发+点赞=支持 ini是啥 你可以理解为就是一个配置文件的统称吧。比如test.conf,这样的你可以理解为他就...

  • Configparser模块的使用

    ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似...

  • python configparser模块

    ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似...

  • Python读取ini配置文件

    配置文件ini的格式 读取ini文件 获取配置文件中对应值的基础方法 实现一个ini配置文件读取工具类

  • Python读取ini配置文件

    配置文件ini的格式 读取ini文件 获取配置文件中对应值的基础方法 实现一个ini配置文件读取工具类

  • ConfigParser:R语言读取脚本配置文件

    我们都知道在python中有标准库 configparser读取config或ini配置文件。有了配置文件脚本少了...

  • python配置

    python读取配置文件方式(ini、yaml、xml) - 云+社区 - 腾讯云 (tencent.com)[h...

  • Python ini配置文件读取

    写在前面的话  写文档其实比敲代码要累,需要组织文章结构,需要想清楚说什么,怎么去表达,这是我最不擅长的事情,但还...

  • python | 读取ini配置文件

    1、配置文件格式如下: 2、引入了python的ConfigParser模块,部分方法如下: 3、使用方法:

  • ConfigParser基本使用

    configparser和ConfigParser在python中用来读取ini类型的配置文件的,提供很多方便的A...

网友评论

    本文标题:通过python读取ini配置文件

    本文链接:https://www.haomeiwen.com/subject/ovayuxtx.html