python_配置文件
发布时间:2020-12-20 10:31:15 所属栏目:Python 来源:网络整理
导读:想把数据库信息抽离到一个ini配置文件中,这样做的好处在于可以在配置文件中添加多个数据库,方便切换(另外配置文件也可以添加诸如邮箱、url等信息) 1.configparser模块 python使用自带的configparser模块用来读取配置文件,配置文件的形式类似windows中的in
1.configparser模块python使用自带的configparser模块用来读取配置文件,配置文件的形式类似windows中的ini文件 在使用前需要先安装该模块,使用pip安装即可 2.configparser读取文件的基本方法(1)新建一个config.ini文件,如下 (2)新建一个readconfig.py文件,读取配置文件的信息 import configparser cf = configparser.ConfigParser() cf.read("E:Crawlerconfig.ini") # 读取配置文件,如果写文件的绝对路径,就可以不用os模块 secs = cf.sections() # 获取文件中所有的section(一个配置文件中可以有多个配置,如数据库相关的配置,邮箱相关的配置, 上述代码运行结果如下,可以和config.ini进行对比? 3.引入os模块,使用相对目录读取配置文件工程目录如下: readconfig.py: import configparser import os root_dir = os.path.dirname(os.path.abspath(‘.‘)) # 获取当前文件所在目录的上一级目录,即项目所在目录E:Crawler cf = configparser.ConfigParser() cf.read(root_dir+"/config.ini") # 拼接得到config.ini文件的路径,直接使用 或者使用os.path.join()进行拼接 import configparser import os root_dir = os.path.dirname(os.path.abspath(‘.‘)) # 获取当前文件所在目录的上一级目录,即项目所在目录E:Crawler configpath = os.path.join(root_dir,"config.ini") cf = configparser.ConfigParser() cf.read(configpath) # 读取配置文件 4.通过读取配置文件,重新写一下之前的requests+正则表达式爬取猫眼电影的例子把读取配置文件readconfig.py和操作数据库handleDB.py分别封装到一个类中 readconfig.py如下 import configparser import os class ReadConfig: """定义一个读取配置文件的类""" def __init__(self,filepath=None): if filepath: configpath = filepath else: root_dir = os.path.dirname(os.path.abspath(‘.‘)) configpath = os.path.join(root_dir,"config.ini") self.cf = configparser.ConfigParser() self.cf.read(configpath) def get_db(self,param): value = self.cf.get("Mysql-Database",param) return value if __name__ == ‘__main__‘: test = ReadConfig() t = test.get_db("host") print(t) handleDB.py如下 # coding: utf-8 # author: hmk from common.readconfig import ReadConfig import pymysql.cursors class HandleMysql: def __init__(self): self.data = ReadConfig() def conn_mysql(self): """连接数据库""" host = self.data.get_db("host") user = self.data.get_db("user") password = self.data.get_db("password") db = self.data.get_db("db") charset = self.data.get_db("charset") self.conn = pymysql.connect(host=host,user=user,password=password,db=db,charset=charset) self.cur = self.conn.cursor() def execute_sql(self,sql,data): """执行操作数据的相关sql""" self.conn_mysql() self.cur.execute(sql,data) self.conn.commit() def search(self,sql): """执行查询sql""" self.conn_mysql() self.cur.execute(sql) return self.cur.fetchall() def close_mysql(self): """关闭数据库连接""" self.cur.close() self.conn.close() if __name__ == ‘__main__‘: test = HandleMysql() sql = "select * from maoyan_movie" for i in test.search(sql): print(i) 最后的运行文件,调用前面的方法 # coding: utf-8 # author: hmk import requests import re from common import handleDB class Crawler: """定义一个爬虫类""" def __init__(self): self.db = handleDB.HandleMysql() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |