.user_profile{ display:block}

模块-json,pickle

# json pickle shelve模块 序列化

# json模块 用在不同语言之间的数据传输,但是限定数据类型:str,int,list,dict,布尔值
import json

# 四种方法:
# dumps和loads:用于网络数据传输 和 多个数据写入一个文件中
dict = {'wo':'good_person','ni':'bad_person'}
ret = json.dumps(dict,ensure_ascii=False) # {"wo": "good_person", "ni": "bad_person"}
# 将dict转换 成 序列化字符串 ensure_ascii=False : 字符串中文可视化
print(ret)

#反序列化
print(json.loads(ret))

dict1 = {'wo':'good_person','ni':'bad_person'}
dict2 = {'wo':'good_person','ni':'bad_person'}
dict3 = {'wo':'good_person','ni':'bad_person'}
#多个数据写入一个文件中
with open('json_files','w',encoding='utf-8') as f:
    ret1 = json.dumps(dict1,ensure_ascii=False)
    f.write(ret1+'\n')
    ret2 = json.dumps(dict2,ensure_ascii=False)
    f.write(ret2+'\n')
    ret3 = json.dumps(dict3,ensure_ascii=False)
    f.write(ret3+'\n')

with open('json_files','r',encoding='utf-8') as f1:
    for line in f1:
        print(json.loads(line))

dict1 = {'wo':'good_person','ni':'bad_person'}
dump和load:用于文件中一个数据写入一个文件中
f = open('json_file','w',encoding='utf-8')
json.dump(dict1,f) # 序列化
f.close()
f = open('json_file','r',encoding='utf-8')
print(json.load(f)) #反序列化

# pickle 用于Python语言之间的数据传输 适用于几乎所有数据类型
import pickle
# dumps loads
dict1 = {'wo':'good_person','ni':'bad_person'}
ret = pickle.dumps(dict1) # bytes类型
print(ret)

print(pickle.loads(ret)) #反序列化

import pickle
dict1 = {'wo':'good_person','ni':'bad_person'}
dict2 = {'wo':'good_person','ni':'bad_person'}
dict3 = {'wo':'good_person','ni':'bad_person'}
# dump load
# 对文件进行读写
# f = open('pickle_files','wb')
# pickle.dump(dict1,f)

with open('pickle_files','rb') as f1:
    while True:
        try:
            print(pickle.load(f1))
        except EOFError:
            break

 

posted @ 2018-07-05 20:03  软萌团子  阅读(102)  评论(0编辑  收藏  举报