1. 程式人生 > 實用技巧 >pickle- json time 模組

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'\x80\x03c__main__\nfunc\nq\x00.'

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("\n")
    json.dump(dic2,fp)
    fp.write("\n")


# 連續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('\r[%-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)