标签:open pickle dump 文件读取 pytho project bin class highlight
用于序列化的两个模块
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
实例一:
1、文件写入
info = { ‘name‘:‘robin‘, ‘old‘:‘12‘ } f = open(‘E:\python-project\ceshi.txt‘,‘w‘) f.write(str(info)) f.close()
2、文件读取
f = open(‘E:\python-project\ceshi.txt‘,‘r‘) data = eval(f.read()) f.close() print(data[‘old‘])
实例二:(使用json序列化)
1、文件写入
import json info = { ‘name‘:‘robin‘, ‘old‘:‘12‘ } f = open(‘E:\python-project\ceshi.txt‘,‘w‘) f.write(json.dumps(info)) #相当于json.dump(info,f) f.close()
2、文件读取
import json f = open(‘E:\python-project\ceshi.txt‘,‘r‘) data = json.loads(f.read()) #相当于data = json.load(f) f.close() print(data[‘old‘])
实力三:(使用pickle序列化)
1、文件写入
import pickle def sas(name): print("hello",name) info = { ‘name‘:‘robin‘, ‘old‘:‘12‘, ‘func‘:sas } f = open(‘E:\python-project\ceshi.txt‘,‘wb‘) f.write(pickle.dumps(info)) #相当于pickle.dump(info,f) f.close()
2、文件读取
import pickle def sas(name): print("hello2",name) f = open(‘E:\python-project\ceshi.txt‘,‘rb‘) data = pickle.loads(f.read()) #相当于data = pickle.load(f) f.close() print(data[‘func‘](‘wen‘))
标签:open pickle dump 文件读取 pytho project bin class highlight
原文地址:https://www.cnblogs.com/bazingafraser/p/8876255.html