一、json模块
作用:将内置的数据类型,如int uplelistdic(set, class不行),进行序列化或反序列化
- dumpsloads方法主要用于网络传输,有时也用来读取文件。用于一般数据结构数据与json字符串相互转换
import json
# 1.将一般数据结构转化成json字符串
dic = {'name':'mkc', 'birth':1993, 'sex':'male'}
s1= json.dumps(dic)
print(s1, type(s1))
# 2.将json字符串写入到文件中
with open('file1.json', mode='a', encoding='utf-8') as f1:
f1.write(s1+'
')
# 3.将json字符串转化成一般的数据类型
dic1 = json.loads(s1)
print(dic1, type(dic1))
print("
")
# 4.将文件中数据读出,再用loads转化成一般的数据类型
with open('file1.json', mode='r', encoding='utf-8') as f2:
while True:
try:
s2 = f2.readline()
dic2 = json.loads(s2)
print(dic2, type(dic2))
except Exception:
break
- dump、load模块
dump/load 只能写入文件,并且一次只能写入一个数据结构
l = [1,2,3,4]
with open('file2.json', encoding='utf-8', mode='w') as f:
json.dump(l, f)
with open('file2.json', encoding='utf-8', mode='r') as f:
l1 = json.load(f)
print(l1, type(l1))
二、pickle模块
语法基本与json一样
不同点:
pickle是一般数据类型与byte类型相互转化
pickle的dumpsloads方法只能用于网络传输,dumpload方法用于读写文件
pickle可以的数据类型为一切对象,不像json那样受到限制
import pickle
class Person():
def __init__(self, name, birth):
self.name = name
self.birth = birth
mkc = Person('mkc', 1993)
s = pickle.dumps(mkc)
p1= pickle.loads(s)
print(p1.name)
# # 尝试写入文件
# with open('file3.pickle', mode='wb', encoding='utf-8') as f: #ERROR
# f.write(s) # ERROR
with open('file3.pickle', mode='wb') as f:
pickle.dump(mkc, f)
with open('file3.pickle', 'rb') as f:
p2 = pickle.load(f)
print(p2.birth)