# 🌈dumps:将python数据转换成为二进制
# 🌈dump:将python数据转换成为二进制,同时保存到指定文件
# 🌈loads:将二进制加载成为python数据
# 🌈load:读取文件,并将文件的内容加载成为二进制
# 🌟dumps,loads
import pickle
info = {'name':'Taxi','age':10}
x = pickle.dumps(info)
file = open('pickle.dumps_test.txt','wb')
file.write(x)
file.close()
file1 = open('pickle.dumps_test.txt','rb')
y = file1.read()
z = pickle.loads(y)
print(z)
file1.close()
# 🌟dump/load
names = ['zhangsan','lisi']
file3 = open('pickle.dump_test.txt','wb')
pickle.dump(names,file3)
file3.close()
file4 = open('pickle.dump_test.txt','rb')
pickle.load(file4)
# 🌟定义一个类:Person,给个属性:name,age;实例化对象:zhangsan,15;
# 利用pickle.dump将此对象写入pickle_test.txt文件中;再利用pickle.load将此对象加载出来
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
p = Person('zhangsan',15)
pickle.dump(p,open('pickle_test.txt','wb'))
content = pickle.load(open('pickle_test.txt','rb')) # {'name': 'Taxi', 'age': 10}
print(content.name)
Python:pickle的使用
最新推荐文章于 2024-08-27 10:11:01 发布