序列化:把內(nèi)存中的數(shù)據(jù)類型轉(zhuǎn)換為字符串,以便能夠存儲(chǔ)到硬盤或通過網(wǎng)絡(luò)傳輸?shù)竭h(yuǎn)程,因?yàn)橛脖P或網(wǎng)絡(luò)傳輸時(shí)只能接受bytes。
反序列化:把硬盤中的數(shù)據(jù)轉(zhuǎn)換為內(nèi)存數(shù)據(jù)類型網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了吉利免費(fèi)建站歡迎大家使用!
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
data = {"haha":"哈哈"}
fw = open(file="寫文件.txt",mode="w",encoding="utf-8")
fw.write(str(data)) # 序列化
fw.close()
fr = open(file="寫文件.txt",mode="r",encoding="utf-8")
d = fr.read()
d = eval(d) # 反序列化
print(d)
fr.close()
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'haha': '哈哈'}
Process finished with exit code 0
優(yōu)點(diǎn):跨語言、體積小
缺點(diǎn):只能支持int\str\list\tuple\dict
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
# dumps并沒有把內(nèi)容寫入到硬盤中
d = json.dumps(data)
print(d,type(d))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{"haha": "\u54c8\u54c8"} <class 'str'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
# dumps并沒有把內(nèi)容寫入到硬盤中
d = json.dumps(data)
d2 = json.loads(d)
print(d2,type(d2))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'haha': '哈哈'} <class 'dict'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
fw = open(file="寫文件.txt",mode="w",encoding="utf-8")
d = json.dump(data,fw)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Process finished with exit code 0
查看文件中的內(nèi)容
{"haha": "\u54c8\u54c8"}
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
fr = open(file="寫文件.txt",mode="r",encoding="utf-8")
d = json.load(fr)
print(d,type(d))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'haha': '哈哈'} <class 'dict'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
data2 = {"hehe":"呵呵"}
fw = open(file="寫文件.json",mode="w",encoding="utf-8")
json.dump(data,fw)
json.dump(data2,fw)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Process finished with exit code 0
查看文件內(nèi)容
{"haha": "\u54c8\u54c8"}{"hehe": "\u5475\u5475"}
多次dump是沒有報(bào)錯(cuò),但是load()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import json
data = {"haha":"哈哈"}
data2 = {"hehe":"呵呵"}
fr = open(file="寫文件.json",mode="r",encoding="utf-8")
print(json.load(fr))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
File "E:/PythonProject/python-test/BasicGrammer/test.py", line 8, in <module>
print(json.load(fr))
File "D:\software2\Python3\install\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "D:\software2\Python3\install\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "D:\software2\Python3\install\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 25 (char 24)
Process finished with exit code 1
"說明不要dump多次,雖然dump不報(bào)錯(cuò),但是load不回來了。因?yàn)樵谝恍杏袃煞N類型的數(shù)據(jù)"
優(yōu)點(diǎn):轉(zhuǎn)為python設(shè)計(jì),支持python所有數(shù)據(jù)類型。
缺點(diǎn):只能在python中使用,存儲(chǔ)數(shù)據(jù)占用空間大。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pickle
data = {"haha":"哈哈"}
d = pickle.dumps(data)
print(d,type(d))
l = pickle.loads(d)
print(l,type(l))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
b'\x80\x03}q\x00X\x04\x00\x00\x00hahaq\x01X\x06\x00\x00\x00\xe5\x93\x88\xe5\x93\x88q\x02s.' <class 'bytes'>
{'haha': '哈哈'} <class 'dict'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pickle
data = {"haha":"哈哈"}
fw = open(file="寫文件.json",mode="wb") #由于dump后數(shù)據(jù)類型是bytes類型,所以mode="wb"
d = pickle.dump(data,fw)
fw.close()
fr = open(file="寫文件.json",mode="rb") #寫入時(shí)是wb,讀取時(shí)是rb
l = pickle.load(fr)
print(l,type(l))
fr.close()
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'haha': '哈哈'} <class 'dict'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pickle
def fun():
print("232")
d = pickle.dumps(fun)
print(d,type(d))
l = pickle.loads(d)
print(l,type(l))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
b'\x80\x03c__main__\nfun\nq\x00.' <class 'bytes'>
<function fun at 0x00000157C0883E18> <class 'function'>
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import pickle
def fun():
print("232")
fw = open(file="寫文件.json",mode="wb")
d = pickle.dump(fun,fw)
fw.close()
fr = open(file="寫文件.json",mode="rb")
l = pickle.load(fr)
print(l,type(l))
fr.close()
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
<function fun at 0x0000017668504C80> <class 'function'>
Process finished with exit code 0
可序列化多次,反序列化多次,就像操作字典一樣操作數(shù)據(jù)
shelve是一個(gè)簡單的k,v將內(nèi)存數(shù)據(jù)通過文件持久化的模塊,可以持久化任何pickle可支持的python數(shù)據(jù)格式
"注意:shelve打開文件時(shí),文件如果是存在的,是會(huì)報(bào)下面的錯(cuò)誤的"
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in <module>
f = shelve.open("寫文件.txt")
File "D:\software2\Python3\install\lib\shelve.py", line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "D:\software2\Python3\install\lib\shelve.py", line 227, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "D:\software2\Python3\install\lib\dbm\__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
Process finished with exit code 1
"shelve序列化"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import shelve
f = shelve.open("寫文件.txt") #此處的文件不能是已經(jīng)存在的
names = ["vita","麗麗","lyly"]
info = {"name":"vita","age":23}
f["names"]=names
f["info_dic"]=info
f.close()
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Process finished with exit code 0
寫入成功后,產(chǎn)生如下的文件
"shelve反序列化"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import shelve
f = shelve.open("寫文件.txt")
print(f["names"])
print(f["info_dic"])
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
['vita', '麗麗', 'lyly']
{'name': 'vita', 'age': 23}
Process finished with exit code 0
"查詢"
>>> f = shelve.open("寫文件.txt")
>>> f
<shelve.DbfilenameShelf object at 0x000002A52DB5E780>
>>> f.keys()
KeysView(<shelve.DbfilenameShelf object at 0x000002A52DB5E780>)
>>> list(f.keys())
['names', 'info_dic']
>>> list(f.items())
[('names', ['vita', '麗麗', 'lyly']), ('info_dic', {'name': 'vita', 'age': 23})]
>>> f.get("names")
['vita', '麗麗', 'lyly']
>>> f.get("info_dic")
{'name': 'vita', 'age': 23}
>>> f["names"][1]
'麗麗'
"修改"
>>> f["names"][1]="超超" #這樣修改是不可以的
>>> f["names"][1] "
'麗麗'
>>> f["names"]=["ccc","lll"] #可以這樣修改
>>> f["names"]
['ccc', 'lll']
>>> f.items()
ItemsView(<shelve.DbfilenameShelf object at 0x000002A52DB5E780>)
>>> list(f.items())
[('names', ['ccc', 'lll']), ('info_dic', {'name': 'vita', 'age': 23})]
"刪除"
>>> del f["names"]
>>> list(f.items())
[('info_dic', {'name': 'vita', 'age': 23})]
"增加"
>>> f["scores"]=[90,89]
>>> list(f.items())
[('info_dic', {'name': 'vita', 'age': 23}), ('scores', [90, 89])]
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)頁題目:json&&pickl&&shelve-創(chuàng)新互聯(lián)
URL分享:http://chinadenli.net/article20/dehejo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站設(shè)計(jì)、服務(wù)器托管、靜態(tài)網(wǎng)站、App設(shè)計(jì)、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容