物件儲存 編碼 解碼

2022-04-30 23:09:18 字數 2104 閱讀 3708

儲存:永久性儲存物件

有時候,我們需要將某些字串、列表、字典、元組等資料⻓久儲存,現

在,這個時候,就需要使⽤

永久性儲存的模組⽂件pickle。pickle模組可以將

物件轉換為⼀種可以儲存或讀取的格式。

pickle:該模組實現了資料的序列化與反序列化,通過pickle的序列化操作,可

以實現將程式中的物件

儲存到⽂件資訊中,實現永久性儲存。通過pickle的

反序列化操作,可以實現將程式中的永久性儲存的物件解析出來

在使用檔案讀取完後一定要把檔案關閉了,如:f1.close()

#

儲存list

#匯入 pickle

import

pickle

list1=[12,2,3]

f1=open('

list.txt

','wb')

#將列表存入到檔案中

#語法格式:

#pickle.dump(儲存的資料,目標檔案)

pickle.dump(list1,f1)

f1.close()

#建議:儲存資料時,盡量不要使用系統能夠開啟的字尾名,

#優點:防止使用者隨意開啟,更改資料

#從檔案中讀取列表

#語法格式:

#pickle.load(儲存的資料,目標檔案)

f2=open("

list.txt

","rb")

list2=pickle.load(f2)

print(list2)

簡寫模式

好處:可以省略關閉檔案這個操作,減少**

#

從檔案中讀取物件

with open("

list.txt

","rb

") as f1:

pickle.load(f1)

#將物件寫如檔案中

with open("

list.txt

","wb

") as f2:

pickle.dump(list1,f2)

編碼/解碼

編碼:檔案.encode(編碼格式)

解碼:檔案.decode(編碼格式)

常見編碼格式  

gb2312是中國規定的漢字編碼,也可以說是簡體中文的字符集編碼

gbk是 gb2312的擴充套件 ,除了相容gb2312外,它還能顯示正體中文,還有日文的假名

cp936中文本地系統是windows中的cmd,預設codepage是cp936,cp936就是指系統裡第936號編碼格式,即gb2312的編碼。

(當然有其它編碼格式:cp950 正體中文、cp932 日語、cp1250 中歐語言。。。)

unicode是國際組織制定的可以容納世界上所有文字和符號的字元編碼方案。utf-8、utf-16、utf-32都是將數字轉換到程式資料的編碼方案。

utf-8(8-bit unicode transformation format)是最流行的一種對 unicode 進行傳播和儲存的編碼方式。它用不同的 bytes 來表示每乙個**點。

ascii 字元每個只需要用乙個 byte ,與 ascii 的編碼是一樣的。所以說 ascii 是 utf-8 的乙個子集。

#

編碼with open("

file2.txt

","wb

") as f1:

str1="

123132djijdi外交誒

"enstr=str1.encode("

utf-8")

print

(enstr)

f1.write(enstr)#解碼

with open("

file2.txt

","rb

") as f2:

str2=f2.read()

destr=str2.decode("

utf-8")

print(destr)

使用Python編碼 解碼JSON物件

測試版本為python2.7 import json pobj print type s content s type pobj pobj jsonstr json.dumps pobj 編碼 print type s content s type jsonstr jsonstr obj json....

使用php編碼和解碼json 物件

在 php5.2.0 及以上版本已經內建 json 擴充套件。函式 描述 json encode 對變數進行 json 編碼 json decode 對 json 格式的字串進行解碼,轉換為 php 變數 json last error 返回最後發生的錯誤 json encode php json ...

編碼 解碼 中文編譯碼

字串和字符集的關係 字串是python程式的一種格式 位元組串是網路傳輸的一種形式 字串和位元組串轉換 字串 str encode 位元組串 bytes 位元組串 bytes decode 字串 str ascii字符集是utf 8字符集的前128位字元,可以說ascii字符集是utf 8字符集的子...