Python常用模块part2

一、json

所有编程语言都能够识别的数据叫做json,是字符串。
能够通过json序列化成字符串的有如下类型:int、bool、float、list、tuple、str、dict、None

import json (导入json模块)

1、dumps

dumps可以将可json序列化类型数据序列化成字符串
ensure_ascii=False 显示中文 sort_keys=True 对字典的键进行排序

import json
dic = {"item":"apple","price":15,"数量":10}
res=json.dumps(dic,ensure_ascii=False)
print(res,type(res))

运行结果:
运行结果

2、loads

反序列化,得到原来的数据类型

import json
dic = {"item":"apple","price":15,"数量":10}
res1=json.dumps(dic,ensure_ascii=False)
print(res1,type(res1))
res2=json.loads(res1)
print(res2,type(res2))

运行结果:
运行结果

3、dump 针对于文件,把数据序列化后存储文件

import json
dic = {"item":"apple","price":15,"数量":10}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="w",encoding="utf-8") as fp:
	json.dump(dic,fp)

文件内容:
文件内容

4、load 将文件中的字符串反序列化成原来的数据

import json
dic = {"item":"apple","price":15,"数量":10}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="r",encoding="utf-8") as fp:
	res=json.load(fp)
	print(res,type(res))

运行结果:
运行结果

5、json和pickle之间的区别

  • (1)json序列化之后的数据类型是str,所有编程语言都识别,
    但是仅限于(int float bool)(str list tuple dict None)
    json不能连续load,只能一次性拿出所有数据

  • (2)pickle序列化之后的数据类型是bytes,
    所有数据类型都可转化,但仅限于python之间的存储传输.
    pickle可以连续load,多套数据放到同一个文件中

  • json使用的广泛性比pickle更强.

  • json 用在不同编程语言的数据交流中

  • pickle 用于数据的存储

首先测试json,将多个字典dump到文件中:

import json
dic1 = {"item":"apple","price":15,"数量":10}
dic2 = {"item":"orange","price":20,"数量":13}
dic3 = {"item":"banana","price":15,"数量":8}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="w",encoding="utf-8") as fp:
	json.dump(dic1,fp)
	fp.write("\n")
	json.dump(dic2,fp)
	fp.write("\n")
	json.dump(dic3,fp)

文件内容如下:
文件内容

此时我们通过load去反序列化获取文件内容:

import json
dic1 = {"item":"apple","price":15,"数量":10}
dic2 = {"item":"orange","price":20,"数量":13}
dic3 = {"item":"banana","price":15,"数量":8}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="r",encoding="utf-8") as fp:
	res=json.load(fp)
	print(res)

运行结果:
运行结果

如图,load 在获取数据时,是一次性拿取所有内容,但json无法连续load,所以导致报错

解决办法:利用循环一行一行取出数据进行反序列化

import json
dic1 = {"item":"apple","price":15,"数量":10}
dic2 = {"item":"orange","price":20,"数量":13}
dic3 = {"item":"banana","price":15,"数量":8}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="r",encoding="utf-8") as fp:
	for i in fp:
		res=json.loads(i)
		print(res)

运行结果:
运行结果

pickle可以连续dump,也可以连续load,因为pickle在存储数据的时候会在末尾加上结束符

import pickle
dic1 = {"item":"apple","price":15,"数量":10}
dic2 = {"item":"orange","price":20,"数量":13}
dic3 = {"item":"banana","price":15,"数量":8}
with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="wb") as fp:
	pickle.dump(dic1,fp)
	pickle.dump(dic2,fp)
	pickle.dump(dic3,fp)

通过load取数据:
扩展:
try :
可能报错的代码
except:
如果报错执行except这个代码块;

import pickle
dic1 = {"item":"apple","price":15,"数量":10}
dic2 = {"item":"orange","price":20,"数量":13}
dic3 = {"item":"banana","price":15,"数量":8}

with open("/Users/atsukokoshi/Desktop/学习记录/ceshi.txt",mode="rb") as fp:
	try:
		while True:
			res=pickle.load(fp)
			print(res)
	except:
		pass

运行结果:
运行结果

二、时间模块

import time (导入时间模块)

1、time

获取本地时间戳

import time
print(time.time())

运行结果:
运行结果

2、localtime

获取本地时间元组,参数是时间戳,默认当前

import time
print(time.localtime())

运行结果:
运行结果

指定时间戳,返回时间元组

import time
print(time.localtime(1596295641.4654982))

运行结果:

运行结果

3、mktime

通过时间元组获取时间戳

import time
ttp = (2020,8,1,23,30,25,0,0,0)
print(time.mktime(ttp))

运行结果:
运行结果

4、ctime

获取时间字符串,默认本地时间字符串,参数是时间戳,默认当前。

import time
print(time.ctime())

运行结果
运行结果

指定时间戳获取时间字符串

import time
print(time.ctime(1596295825.0))

运行结果
运行结果

获取顺序:localtime -> mtkime -> ctime(时间元组->时间戳->时间字符串)

5、asctime(了解)

通过时间元组获取时间字符串,不能自动识别周几

import time
ttp = (2020,8,1,11,37,40,0,0,0)
print(time.asctime(ttp))

运行结果
运行结果

改造办法:

import time
ttp = (2020,8,1,11,37,40,0,0,0)
res=time.mktime(ttp)
new_res=time.ctime(res)
print(new_res)

运行结果:
运行结果

6、sleep

睡眠等待时间

import time
start=time.time()
print("两秒后执行")
time.sleep(2)
print("执行完毕")
end=time.time()
res = end-start
print("共执行{:.2f}秒!".format(res))

运行结果:
运行结果

7、strftime

格式化时间字符串(格式化字符串,时间元组)

import time
res=time.strftime("%Y-%m-%d %H:%M:%S")
print(res)

运行结果:
运行结果

指定时间元组格式化字符串:

import time
ttp=(2020,8,1,23,50,32,0,0,0)
res=time.strftime("%Y-%m-%d %H:%M:%S",ttp)
print(res)

运行结果:
运行结果

8、strptime

将时间字符串通过指定格式提取到时间元组中(时间字符串,格式化字符串)

import time
strvar="Wsir出生于2000年1月1日20时10分45秒"
ttp=time.strptime(strvar,"Wsir出生于%Y年%m月%d日%H时%M分%S秒",)
print(ttp)

运行结果:
运行结果

格式化定义字符:
%Y 年 year
%m 月 month
%d 日 day
%H 时 hour
%M 分 minute
%S 秒 second

strftime: 将时间元组转换为时间字符串
strptime: 将时间字符串转换为时间元组

9、perf_counter (了解)

用于计算程序运行时间
记录开始时间:

import time
starttime=time.perf_counter()
print(starttime)

运行结果:
运行结果

此方法可用time代替。

10、进度条效果

引入时间模块完成进度条效果

引入时间模块完成进度条效果:
```python
import time
strvar = ""
for i in range(51):
	time.sleep(0.1)
	strvar += "#"
	print("\r[%-50s] %d%%" %(strvar,i*2),end="")

运行结果:
运行结果

三、zipfile 压缩模块

1、创建压缩包

import zipfile
zf=zipfile.ZipFile("/Users/atsukokoshi/Desktop/学习记录/ceshi.zip","w",zipfile.ZIP_DEFLATED)
zf.write("/Users/atsukokoshi/Desktop/学习记录/ceshi2.txt","ceshi2")
zf.write("/Users/atsukokoshi/Desktop/学习记录/ceshi3.txt","ceshi3")
zf.close()

成功在相应绝对路径下创建压缩包

2、解压压缩包

import zipfile
zf=zipfile.ZipFile("/Users/atsukokoshi/Desktop/学习记录/ceshi.zip","r")
zf.extract("ceshi2","/Users/atsukokoshi/Desktop/学习记录/ceshi222.txt")
zf.extractall("/Users/atsukokoshi/Desktop/学习记录/ceshi")
zf.close()

成功在相应路径下解压压缩包。
运行结果

3、追加文件

支持with语法

import zipfile
with zipfile.ZipFile("/Users/atsukokoshi/Desktop/学习记录/ceshi.zip","a") as zf:
	zf.write("/Users/atsukokoshi/Desktop/学习记录/ceshi5.txt","ceshi5")

成功追加ceshi5.txt至压缩文件中

4、namelist 查看压缩包中文件

import zipfile
with zipfile.ZipFile("/Users/atsukokoshi/Desktop/学习记录/ceshi.zip","r") as zf:
	res=zf.namelist()
	print(res)

运行结果:
运行结果
成功获取压缩包文件。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值