溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中序列化與數(shù)據(jù)持久化的示例分析

發(fā)布時(shí)間:2021-07-16 14:06:47 來源:億速云 閱讀:151 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹python中序列化與數(shù)據(jù)持久化的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

具體如下:

數(shù)據(jù)持久化的方式有:

1.普通文件無格式寫入:將數(shù)據(jù)直接寫入到文件中

2.普通序列化寫入:json,pickle

3.DBM方式:shelve,dbm

相關(guān)內(nèi)容:

  • json

  • pickle

  • shelve

  • dbm

json:

介紹:

按照指定格式【比如格式是字典,那么文件中就是字典】將數(shù)據(jù)明文寫入到文件中,類型是bytes的,比如”中文“就會(huì)變成Unicode編碼

python中序列化與數(shù)據(jù)持久化的示例分析

用法:

  • 首先要導(dǎo)入模塊import json

  • 序列化:

    • json.dump(序列化對象,文件對象)

    • json.dumps(序列化對象),返回值是一個(gè)字符串,需要手動(dòng)將這個(gè)字符串寫入到文件中

print("------json序列化--------")
import json
import time
info={
  'date':time.localtime(),
  'name':'中文'
}
f=open("test.txt","w")
print("---------dump---------")
# json.dump(info,f)
# f.close()
print("---------dumps,---------")
f.write(json.dumps(info))
f.close()
  • 反序列化:

    • json.load(文件對象)

    • json.loads(字符串)

print("------反序列化--------")
import json
f=open("test.txt","r")
print("-------load----------")
# data=json.load(f)#1
# print(data)
print("-------loads----------")
d2=json.loads(f.read())
print(d2)
f.close()

對于多次dump\dumps,如何load\loads取出來:

  • 需要在dump的時(shí)候,手動(dòng)對數(shù)據(jù)進(jìn)行劃分

print("------json序列化--------")
import json
import time
info={
  'date':time.localtime(),
  'name':'中文'
  # 'func':hello #注:json不可序列化函數(shù)
}
info2=['1',2,3,4]
f=open("test.txt","w")
print("---------dumps,---------")#用'\n'來區(qū)分兩份數(shù)據(jù)
f.write(json.dumps(info)+"\n")
f.write(json.dumps(info2)+"\n")
f.close()
import json
with open("test.txt") as f:
  a=json.loads(f.readline())
  b=json.loads(f.readline())
  print(a,b)

pickle:

介紹:

  • 用于實(shí)現(xiàn)Python數(shù)據(jù)類型與Python特定二進(jìn)制格式之間的轉(zhuǎn)換

  • 參數(shù)protocol規(guī)定了序列化的協(xié)議版本,默認(rèn)情況下使用pikkle序列化數(shù)據(jù)是bytes的,打開文件的方式必須為二進(jìn)制格式

用法:

  • 首先導(dǎo)入模塊import pickle

  • 序列化:

    • pickle.dump(序列化對象,文件對象)

    • pickle.dumps(序列化對象),返回值是一個(gè)字符串,需要手動(dòng)將這個(gè)字符串寫入到文件中

import pickle
info={
  'name':'1',
  'age':2,
}
f=open("test2.txt","wb")
pickle.dump(info,f)#序列化方法1
# f.write(pickle.dumps(info))#序列化方法2
f.close()
  • 反序列化:

    • pickle.load(文件對象)

    • pickle.loads(字符串)

print("------反序列化--------")
import pickle
f=open("test2.txt","rb")
data=pickle.loads(f.read())#反序列方法1
print(data)
# data=pickle.load(f)#反序列方法2
# print(data)
f.close()

shelve:

介紹:

  • 專門用于將Python數(shù)據(jù)類型的數(shù)據(jù)持久化到磁盤,操作類似于dict

用法:

  • 首先導(dǎo)入模塊import

  • shelve打開一個(gè)文件: shelve文件對象 = shelve.open(文件名)

  • 寫入:shelve文件對象[key]=value

  • 讀出:shelve文件對象.get(key)

import shelve,time
d = shelve.open('shelve_test') # 打開一個(gè)文件
print("----------寫----------")
info ={"name":'lilei',"sex":"man"}
name = ["autuman", "zhangsan", "lisi"]
d["teacher"] = name
d["student"] = info
d["date"] = time.ctime()
print("--------讀------------")
print(d.get("teacher"))
print(d.get("student"))
print(d.get("date"))
d.close()

shelve可以很方便的序列化自定義的數(shù)據(jù)類型、函數(shù):

import shelve,time
class A:
  def hello(self):
    print("123")
d = shelve.open('shelve_test') # 打開一個(gè)文件
print("----------寫----------")
d['class'] =A
print("--------讀------------")
a=d.get('class')()
a.hello()
d.close()

dbm:

介紹:

  • dbm與shelve非常類似,但dbm的鍵和值必須是字符串類型

  • dbm默認(rèn)寫入的數(shù)據(jù)是bytes的,將所有字符串都序列化成bytes的

用法:

  • 首先導(dǎo)入模塊imort dbm【注意的是由很多個(gè)不同的dbm,可以選擇來使用,這里使用默認(rèn)】

  • 打開文件:dbm對象=dbm.open(文件名,打開模式)

python中序列化與數(shù)據(jù)持久化的示例分析

  • 寫入:dbm對象[key]=value

  • 讀取: dbm對象[key]

import dbm
db=dbm.open("test.txt","c")
print("寫".center(50,'-'))
db["name"]="1111111111112"
db["name2"]="2222222222222"
print("讀".center(50,'-'))
print(db["name"])
print(db["name2"])
db.close()

以上是“python中序列化與數(shù)據(jù)持久化的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI