Python和JSON、yaml、excel、配置文件、logging

一、python数据和json数据的不同点

1、python中的列表:[];在json中叫做数组:Array
2、python中的字典:{key:value};在json中叫做对象:object
3、python中的布尔值:True、False;在json中的布尔值:true、false
4、python中的空值:None;在json中的空值:null
5、json中的引号,统一使用双引号

二、python数据和json数据类型的转换

import json

1、json.dumps:将python中的数据转换为 json数据

li = [None, False, {'aa': True}]
res = json.dumps(li)
print(res, type(res))

2、json.loads:将json数据转换为python中的数据

jstr = '[null, false, {"aa": true}]'
res = json.loads(jstr)
print(res, type(res))

3、json.load:加载json文件,转换为python对应的数据格式

with open(r'C:\project\test.json', 'r', encoding='utf-8')as f:
    res = json.load(f)
print(res)

4、json.dump:将python数据,写入json文件(自动化转换格式)

data = {"name": "testleaf", "age": True, "sex": False, "price": None}
with open(r'C:\project\test.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

三、yaml格式数据

1、列表:

- 11
- 22
- 33
- 44
- name: 'testleaf'
  age: '18'

2、字典:

name: testleaf
age: 18
lists:
  - 11
  - 22
  - 33

四、yaml文件的读写

pip install pyYAML

1、从yaml文件读取数据:yaml.load

import yaml

with open('data.yaml','r') as f:
    res = yaml.load(stream=f,Loader=yaml.FullLoader)
    print(res)

2、将数据写入yaml文件:yaml.dump

import yaml

cases = [{"name":"testleaf","age":18},{"name":"leaf","age":19}]
with open('data_save.yaml', 'w', encoding='utf-8') as f:
    yaml.dump(cases, f, allow_unicode=True)

五、excel文件的读写

pip install openpyxl

只支持xlsx格式文件,不支持xls格式文件;

excel中的三大对象:
WorkBook:工作簿对象
Sheet:表单对象
Cell:格子对象

import openpyxl

1、加载excel文件为一个工作簿对象(workbook)

wb = openpyxl.load_workbook(filename=r'C:\project\data\data.xlsx')

2、选中要读取的表单

login_sh = wb['login']

3、读取表格中的数据(通过指定行、列取获取格子对象)

res = login_sh.cell(row=1,column=1)

4、获取格子中的数据(格子对象的value属性)

data = res.value
print(data)

5、往指定行、列的格子中写入数据

login_sh.cell(row=3,column=2,value='testleaf')

6、将最新的工作薄对象保存为文件

wb.save(filename=r'C:\project\data\data.xlsx')

7、批量读取表单中的数据

import openpyxl

# 1、加载文件为工作簿对象
wb = openpyxl.load_workbook(filename=r'data\data.xlsx')
# 2、选中表单
login_sh = wb['login']

# 3、按行获取表单所有的格子对象--获取出来的数据时列表嵌套元组的格式
rows = login_sh.rows
datas = list(rows)

# 4、遍历读取出来的数据
for item in datas:
    # 遍历出来的item 是每行的所有格子对象
    print(item)
    for c in item:
        # c 是一个格子对象
        print(c.value)

# 5、将所有的数据读取出来组装为列表嵌套列表的格式:优化版
new_list = []
# 遍历读取出来的数据
for item in datas:
    li = []
    # 遍历出来的item 是每行的所有格子对象
    for c in item:
        # c 是一个格子对象
        li.append(c.value)
    print('li:', li)
    # 将这一行的数据添加到new_list中
    new_list.append(li)
print(new_list)

# 6、将所有的数据读取出来组装为列表嵌套列表的格式:使用列表推导式的优化版
new_list = [[c.value for c in item] for item in datas]
print(new_list)

六、配置文件:ini、conf、cfg

1、配置文件一般有ini、conf、cfg的文件格式;
配置文件实例:

[mysql]
default-character-set=utf8

[mysqld]
port=3306
max_connections=200
user=testleaf
sex=True

2、为什么要做配置文件?
将所有的代码和配置都变成模块化可配置化,这样就提高了代码的重用性,不用每次都去修改代码内部,这个就是我们逐步要做的事情,可配置化。
3、场景举例:
(1)多处地方需要用同一个参数,这个时候最好是配置化,这样改动一处就可以了;
(2)如果是经常会变化的变量,我们也可以做这个配置。—>与参数化要区分开来!
4、配置文件的读取

from configparser import ConfigParser

# 创建一个配置文件解析器对象
conf = ConfigParser()
# 通过解析器去解析配置文件
filepath = r'C:\project\data\testleaf.ini'
conf.read(filepath, encoding='utf-8')

# ===========读取配置文件中的配置;传参:配置块、配置项====================
# 1、get方法:读取出来的数据是字符串
res = conf.get('mysqld', 'user')
print(res, type(res))

# 2、getint :  # ----->int(get()):读取出来的数据是int类型的数据
res = conf.getint('mysqld', 'port')
print(res, type(res))


# 3、getfloat :  # ----->float(get()):读取出来的数据是float类型的数据
res = conf.getfloat('mysqld', 'port')
print(res, type(res))

# 4、getboolean: # ----->bool(get()):读取出来的数据是bool类型的数据
res = conf.getboolean('mysqld', 'sex')
print(res,type(res))

5、配置文件的写入与修改

from configparser import ConfigParser

# 1、创建一个配置文件解析器对象
conf = ConfigParser()
# 2、通过解析器去解析配置文件
filepath = r'C:\project\data\testleaf.ini'
conf.read(filepath, encoding='utf-8')

# 3、往配置文件中写入数据;传参:配置块、配置项、值;没有就添加,有就修改
conf.set('mysqld', 'saying', 'hello python')

# 4、将写入的内容保存到配置文件
with open(filepath, 'w', encoding='utf-8') as f:
    conf.write(f)

6、常用方法【section:配置项、option:配置块】
read(filename):直接读取文件内容
sections():得到所有的section,并以列表的形式返回
options(section):得到该section的所有option
items(section):得到该section的所有键值对
get(section,option):得到section中option的值,返回为string类型
getint(section,option):得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat()函数。

七、logging日志模块

1、logging模块日志级别介绍
日志一共分成5个等级,从低到高分别是:

级别说明
DEBUG输出详细的运行情况,主要用于调试
INFO确认一切按预期运行,一般用于输出重要运行情况
WARNING一些意想不到的事情发生了(比如:“警告:内存空间不足”),但是这个软件还能按期工作,在不久的将来会出现问题
ERROR发生了错误,软件没能执行一些功能,还可以继续执行
CRITICAL一个严重的错误,表明程序本身可能无法继续运行
这5个等级,也分别对应5种打日志的方法:debug、info、warning、error、critical。默认的是WARNING,当在WARNING或之上时才被跟踪。
logging模块中默认的日志收集器root,收集日志的等级默认是warning;
更改收集日志的默认等级:logging.root.setLevel('DEBUG')
import logging
logging.root.setLevel('DEBUG')
logging.debug('debug级别的日志')
logging.info('info级别的日志')
logging.warning('warning级别的日志')
logging.error('error级别的日志')
logging.critical('critical级别的日志')

2、logging模块日志收集器的创建
在这里插入图片描述

import logging

# 1、日志收集器的创建:logging.getLogger(名称)
http_log = logging.getLogger('TESTLEAF')

# 2、设置日志收集的等级为DEBUG:规定日志收集等级
http_log.setLevel('DEBUG')

# 3、创建一个日志输出渠道(控制台)
sh = logging.StreamHandler()
sh.setLevel('DEBUG') # 规定日志控制台输出等级
# 4、将日志输出渠道添加到日志收集器中
http_log.addHandler(sh)

# 5、创建一个日志输出渠道(文件)
fh = logging.FileHandler(r'logs\testleaf.log', encoding='utf-8')
fh.setLevel('ERROR') # 规定日志文件输出等级
# 6、将日志输出渠道添加到日志收集器
http_log.addHandler(fh)

http_log.debug('----------DEBUG-------------')
http_log.info('----------info-------------')
http_log.warning('----------warning-------------')
http_log.error('----------error-------------')
http_log.critical('----------critical-------------')

3、logging模块日志输出格式
可以通过logging.Formatter指定日志的输出格式,这个参数可以输出很多有用的信息,如下:
%(name)s:收集器名称
%(levelno)s:打印日志级别的数值
%(levelname)s:打印日志级别名称
%(pathname)s:打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s:打印当前执行程序名
%(funcName)s:打印日志的当前函数
%(lineno)d:打印日志的当前行号
%(asctime)s:打印日志的时间
%(thread)d:打印线程ID
%(threadName)s:打印线程名称
%(process)d:打印进程ID
%(message)s:打印日志信息
在工作中给的常用格式如下:

formats = '%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s'

这个格式可以输出日志的打印时间,是哪个模块的哪一行输出的,输出的日志级别是什么,以及输出的日志内容。

import logging

# 1、日志收集器的创建:logging.getLogger(名称)
http_log = logging.getLogger('TESTLEAF')
# 2、设置日志收集的等级为DEBUG
http_log.setLevel('DEBUG')

# 创建一个日志输出的格式
mats='%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s'
mat= logging.Formatter(mats)

# 3、创建一个日志输出渠道(控制台)
sh = logging.StreamHandler()
sh.setLevel('DEBUG')
sh.setFormatter(mat) # 为日志输出渠道设置日志输出的格式
# 4、将日志输出渠道添加到日志收集器中
http_log.addHandler(sh)

# 5、创建一个日志输出渠道(文件)
fh = logging.FileHandler(r'logs\testleaf.log', encoding='utf-8')
fh.setLevel('ERROR')
fh.setFormatter(mat) # 为日志输出渠道设置日志输出的格式
# 6、将日志输出渠道添加到日志收集器
http_log.addHandler(fh)

http_log.debug('----------DEBUG---一一----------')
http_log.info('----------info--------二二-----')
http_log.warning('----------warning-----三三--------')
http_log.error('----------error-------四四------')
http_log.critical('----------critical-----五五--------')

4、日志轮转
(1)按文件大小轮转:logging.handlers.RotatingFileHandle

# 创建一个按文件大小轮转的文件输出渠道
fh = RotatingFileHandler(filename = 'testleaf.log',
						 encoding = 'utf-8',
						 maxBytes = 1024 * 1024 * 20,
						 backupCount = 3)

参数详解:
maxBytes:设置文件的大小(单位:字节),超过这个大小,就创建新的日志文件;
1024B = 1KB
1024KB = 1MB
backupCount:轮转的文件数量,超过这个数量就删掉最早的;

import logging
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler

# 5、创建一个日志输出渠道(输出到文件的轮转器)
fh = RotatingFileHandler(filepath, maxBytes=300, backupCount=3, encoding='utf-8')
fh.setLevel(f_level)
fh.setFormatter(mat)
# 6、将日志输出渠道添加到日志收集器
http_log.addHandler(fh)

最前面的是最新的:
在这里插入图片描述
(2)按时间轮转:logging.handlers.TimedRotatingFileHandler

# 创建一个按时间轮转的文件输出渠道
fh = TimedRotatingFileHandler(filename = 'testleaf.log',
							  encoding = 'utf-8',
							  when = 'D',
							  interval = 7,
							  backupCount = 10)

参数详解:
interval:设置时间间隔
when:设置间隔单位(默认H)
S - Seconds(秒)
M - Minutes(分钟)
H - Hours(小时)
D - Days(天)
backupCount:轮转的文件数量
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

testleaf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值