1.对象序列化和反序列化
对象序列化:将对象这种抽象概念转化为可以传输存储的物理概念
对象反序列化:将磁盘或者网络间的物理数据转化为对应的编程语言的对象
对象持久化:将对象永久的存储下来
对相反持久化: 将磁盘上永久存储的数据读取内存中
pickle:
将对象序列化为字节数据
dump() ----对象序列化
dumps()
load()
loads() ----对象反序列化
json:
将对象序列化转化为字符数据
dump() ----对象序列化
dumps()
load()
loads() ----对象反序列化
2.pickle-- dumps():
将对象序列化为字节数据
dump() ----对象序列化
dumps()
>>> users
['qf', 'dy', 'xz', 'zjl']
>>> import pickle
>>> pickle.dumps(users)
b'\x80\x04\x95\x1a\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x02qf\x94\x8c\x02dy\x94\x8c\x02xz\x94\x8c\x03zjl\x94e.'
>>> comtent = pickle.dumps(users)
>>> comtent
b'\x80\x04\x95\x1a\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x02qf\x94\x8c\x02dy\x94\x8c\x02xz\x94\x8c\x03zjl\x94e.'
>>> f = open("d:\\a.txt", "bw")
>>> f.write(comtent)
37
>>> f.flush()
在d盘中创建a.txt
3.pickle-- loads():
将对象序列化为字节数据
load()
loads() ----对象反序列化
>>> help(pickle.loads)
Help on built-in function loads in module _pickle:
loads(data, /, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=())
Read and return an object from the given pickle data.
The protocol version of the pickle is detected automatically, so no
protocol argument is needed. Bytes past the pickled object's
representation are ignored.
Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
which are used to control compatibility support for pickle stream
generated by Python 2. If *fix_imports* is True, pickle will try to
map the old Python 2 names to the new names used in Python 3. The
*encoding* and *errors* tell pickle how to decode 8-bit string
instances pickled by Python 2; these default to 'ASCII' and 'strict',
respectively. The *encoding* can be 'bytes' to read these 8-bit
string instances as bytes objects.
>>> f = open("d:\\a.txt", "br")
>>> res = f.read()
>>> res
b'\x80\x04\x95\x1a\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x02qf\x94\x8c\x02dy\x94\x8c\x02xz\x94\x8c\x03zjl\x94e.'
>>> pickle.loads(res)
['qf', 'dy', 'xz', 'zjl']
4.pickle--dump load
>>> import pickle
>>> pickle.dump(users, open("d:\\b.txt","bw"))
>>>
>>>
>>> pickle.load(open("d:\\b.txt","br"))
['qf', 'dy', 'xz', 'zjl']
>>>
5.json--dump,load
>>> import json
>>> json.dump(users, open("d:\\a.txt", "w"))
>>>
>>>
>>> json.load(open("d:\\a.txt", "r"))
['qf', 'dy', 'xz', 'zjl']
>>>
6.with模块---防止忘记关闭IO流
with open("a.txt.txt", "r", encoding="utf-8") as f: #f = open()
content = f.read()
print(content)
i love China
Process finished with exit code 0