pickle- json time 模块

一 . pickle序列化模块

'''

序列化    :  把不能够直接存储的在文件中的数据变得可存储

反序列化 : 把存储的数据拿出来恢复成原来大数据类型

需要配合文件操作     使用dump 和load

不需要配合文件操作  使用dumps 和 loads

'''

引入 import pickle

1.dump 把对象序列化后写入file-like objext(即文件对象)

lst = [1,2,3,4]
with open('ceshi.txt',mode='wb') as fp:
    pickle.dump(lst,fp)

2. load 把file -like object(即文件对象)中的内容拿出来,反序列化成原理数据

with open('ceshi.txt',mode='rb')as fp:
    res = pickle.load(fp)
print(res,type(res))

3. dumps 把任意对象序列化成一个bytes(字节流)

# 序列化函数

def func():
    print('我是func函数')


res = pickle.dumps(func)
print(res)
# 打印:b'x80x03c__main__ func qx00.'

4. loads 把任意字节流反序列化成原来数据

# 反序列化函数字节流

func = pickle.loads(res)
func()

# 我是func函数 ... 

5. 序列化迭代器

from collections import Iterator,Iterable
it = iter(range(10))
print(isinstance(it,Iterator))

# True

6 .反序列化

it = pickle.loads(res1)
print(next(it))
print(next(it))
print(next(it))

# 0,1,2

7 . 使用dumps 和 loads 将数据存储到文件中

with open('ceshi1.txt',mode='wb')as fp:
    res1 = pickle.dumps(it)
    fp.write(res1)



with open('ceshi.txt',mode='rb')as fp:
    res = fp.read()
    it = pickle.loads(res)

print(next(it))
print(next(it))
print(next(it))

# 3,4,5 因为基于上一次打印 

二 . json 模块

'''
# 所有编程语言都能识别的数据格式叫做json,是字符串
能够转换的数据格式: int float bool str list tuple dict None


json  : 一般用来做数据的传输,序列化成字符串
pickle: 一般用来做数据的存储,序列化成字节流
'''
先引入: import json

1. json中的 dumps 和 loads 序列化

dic = {"name":"于盛林","age":25,"sex":"男性","family":["老于","小鱼","小小鱼"]}
ensure_ascii = False 显示中文 ,sort_keys = False 对字典的键进行排序
res = json.dumps(dic,ensuer_ascii = False,sort_keys = True)
print(res,type(res))
# {"age": 25, "family": ["老于", "小鱼", "小小鱼"], "name": "于盛林", "sex": "男性"} <class 'str'>
# 是个字符串

2.反序列化

dic = json.loads(res)
print(tdic,type(dic))



#{'age': 25, 'family': ['老于', '小鱼', '小小鱼'], 'name': '于盛林', 'sex': '男性'} <class 'dict'>
# 是个字典 

3. json中的dump 和 load 

with open('ceshi2.txt',mode='w',encoding='utf-8') as fp:
    json.dump(dic.fp,ensuer_ascii=False)

#{"name": "于盛林", "age": 25, "sex": "男性", "family": ["老于", "小鱼", "小小鱼"]}
with open('ceshi2.txt',mode='r',encoding='utf-8')as fp:
    dic = json,load(fp)
print(dic,type(dic))



# {'name': '于盛林', 'age': 25, 'sex': '男性', 'family': ['老于', '小鱼', '小小鱼']} <class 'dict'>

4 json 和 pickle 之间的区别

1. json

json 可以连续dump ,但是不能连续的load
load是一次性把所有数据拿出来反序列化成原来的数据类型
# 连续dump
with open("ceshi3.txt",mode="w",encoding="utf-8") as fp:
    json.dump(dic1,fp)
    fp.write("
")
    json.dump(dic2,fp)
    fp.write("
")


# 连续load error 
"""
with open("ceshi3.txt",mode="r",encoding="utf-8") as fp:
    json.load(fp)
    json.load(fp)
"""


解决:
with open("ceshi3.txt",mode="r",encoding="utf-8") as fp:
    for i in fp:
        dic = json.loads(i)
        print(dic, type(dic))
View Code

2.pickle

pickle 可以连续dump,也能连续的load
import pickle
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
# 连续dump
with open("ceshi4.txt",mode="wb") as fp:
    pickle.dump(dic1,fp)
    pickle.dump(dic2,fp)
    
# 连续load
with open("ceshi4.txt",mode="rb") as fp:
    dic1 = pickle.load(fp)
    print(dic1 , type(dic1))
    dic2 = pickle.load(fp)
    print(dic2 , type(dic2))


# 异常处理的使用
"""
try ... except .. 把有问题的代码写在try代码块中,如果报错执行except 代码块,抑制错误.不会导致程序中断;
"""

# 一次性把所有数据全部拿取出来
with open("ceshi4.txt",mode="rb") as fp:
    try:
        while True:            
            dic = pickle.load(fp)
            print(dic , type(dic))
    except:
        pass
View Code

5. json 和 pickle 两个模块的区别

(1) json序列化之后的数据类型str,所有编程语言都识别,
    但是仅限于(int dloat bool)(str list tuple dict None)
    json不能连续load,只能一次性拿出所有数据
(2) pickle序列化之后的数据类型是字节流
    所有数据类型都可转换,但仅限于python之间的存储传输
    pickle可以连续load,多套数据放在同一文件中

三. time 时间模块

引入 import time

1. time()  获取本地时间戳

res = time.time()
print(res)
View Code

# localtime => mktime => ctime
# 返回元组 => 返回时间戳 => 时间字符串

2 .localtime()     获取本地时间元组 

res = time.localtime()
print(res)

# 指定时间戳
ttp = time.localtime(1600000000)
print(ttp)
View Code

3. mktime()  通过时间元组获取时间戳     (参数是时间元组)

ttp = (2020,12,9,11,5,59,0,0,0)
res = time.mktime(ttp)
print(res)

# 1607483159.0
View Code

4. ctime()     获取本地时间字符串(参数是时间戳,默认当前)

res = time.ctime()
print(res)

# 指定时间戳
res = time.ctime(1607483159.0)
print(res)
View Code

5. sleep()         程序睡眠等待

time.sleep(2)
print('我睡醒了')
View Code

# 注意:=> strftime 时间元组 => 时间字符串 

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

"""linux支持中文显示,windows默认不支持"""

res = tie.strftime('你好 :%Y-%m-%d %H:%M:%S ')
print(res)


# 指定时间元组格式化字符串
ttp = (2021,12,9,11,5,59,0,0,0)
res = time.strftime('你好: %Y-%m-%d %H:%M:%S')
print(res)
View Code

# 注意:=> strptime 时间字符串 => 时间元组

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

"""字符串必须严丝合缝,不能随便加空格;否则报错"""

strvar1="著名的NBA球星霍华德的生日是2020年12月8号,在家里的泳池中下午15点30分40秒开派对"
strvar2="著名的NBA球星霍华德的生日是%Y年%m月%d号,在家里的泳池中下午%H点%M分%S秒开派对"
res = time.strptime(strvar1,strvar2)
print(res)
View Code

8. perf_counter()  用于计算程序运行的时间 (了解)

startime = time.time()
# startime = time.perf_counter()
for i in range(10000000):
    pass
endtime = time.time()
# endtime = time.perf_counter()
print("用的时间是{}".format(endtime-startime))
View Code

四 压缩模块zipfile 

引入 import zipfile

1.创建压缩包

#(1)打开压缩包
zf = zipfile.ZipFile('ceshi100.zip','w',zipfile.ZIP_DEFLATED)
# zf.write(路径,别名)
# (2) 写入文件
zf.write("/bin/chmod","chmod")
zf.write("/bin/cat","cat")
zf.write("/bin/chown","tmp/chown")
# (3) 关闭文件
zf.close()

2.解压文件

zf = zipfile.ZipFile('ceshi100.zip','r')
# 解压所有extractall(路径)
# zf.extractall('ceshi100')
zf.exrract('cat','ceshi200')
zf.close()

3. 查看压缩包 支持with语法(自动实现close操作,不需要手动)

with zipfile.ZipFile('ceshi100.zip','r') as zf:

  lst = zf.namelist()

  print(lst)

4 .追加模式

with zipfile.ZipFile('ceshi100.zip','a',zipfile.ZIP_DEFLATED)
    zf.write("/bin/ln","ln")

5.进度条效果

引入 import time
def progress(percent):
    #如果传入的比列超过100%,强制等于100%
    if percent > 1:
        precent = 1
    strvar = int(50 * percent) * '#'
    print('
[%-50s] %d%%' % (strvar,percent * 100),end='')


recv_data = 0
total = 1024
while recv_data < total:
    # 延迟0.1秒
    time.sleep(0.1)
    recv_data += 100
    # 比列 = 接受数据的大小  / 总大小
    percent = recv_data / total
    # 把比列扔给progress,显示实际的进度条效果;
    progress(percent)

 

原文地址:https://www.cnblogs.com/whc6/p/14111085.html