pickle json 儲存python型別資料

2021-10-01 12:26:49 字數 1149 閱讀 2008

pickle 模組可以儲存任意型別的python資料,包括類變數,陣列,字元等等。

用法也很簡單。

乙個簡單的**如下:

import pickle

class

test

(object):

test1 =

'test'

instance = test(

)instance.test1 =

'this is a test'

with

open

('test.pkl'

,'wb'

)as f:

data = pickle.dumps(instance)

f.write(data)

with

open

('./test.pkl'

,'rb'

)as f:

data = f.read(

) instance_read = pickle.loads(data)

print

(instance_read.test1)

輸出:

this is a test
但是pickle模組本身並不安全,只有當資料****可靠時才可以使用,避免使用處理**不可靠,或者被篡改的資料。一般情況下建議使用json模組,但是json模組只支援python經典的資料結構,像類變數這種無法使用json儲存。

json的使用也非常簡單。例子如下:

import json

test =

with

open

('test.json'

,'w'

)as f:

data = json.dumps(test)

f.write(data)

with

open

('test.json'

,'r'

)as f:

data = f.read(

) test_read = json.loads(data)

print

(test_read)

輸出:

ElasticSearch查詢方法(python)

es.search index my index doc type test type 或者 body es.search index my index doc type test type body body term body 查詢name python 的所有資料 es.search inde...

robot framework自定義python庫

自定義python庫的好處 robot framework填表式,將python的靈活性弄沒了,但是不要擔心,rf早就想到了解決辦法,就是擴充自己的庫.1.在python應用程式包目錄下建立乙個新包 d python27 lib site packages newlibrary 這裡注意資料夾new...

itemcf的hadoop實現優化 Python

原始資料如下 u1 a,d,b,c u2 a,a,c u3 b,d u4 a,d,c u5 a,b,c 計算公式使用 sim u i u j u i u j 其中 u i u j u i u j u i u j 原始的hadoop實現需要5輪mr,優化後只需要兩輪就可以完成。之前的輪數過多,主要在於...