Python 序列化操作

2019-09-28  本文已影响0人  陈忠俊

1. json 操作写字典到文件

>>> import json
>>> import os
>>> info = {"name": "eclipse", "age": 22, "sex": "M"}
>>> f = open("./tmp.txt", "w")
>>> json.dump(info, f)
>>> f.close()
>>> os.system("cat ./tmp.txt")
{"name": "eclipse", "age": 22, "sex": "M"}0
>>>

从文件中读出字典

>>> f = open("./tmp.txt", "r")
>>> handler = json.load(f)
>>> handler
{'name': 'eclipse', 'age': 22, 'sex': 'M'}
>>>

当然我们也可以把字典直接转成字符串

>>> info_str = json.dumps(info)
>>> type(info_str)
<class 'str'>
>>> info_str
'{"name": "eclipse", "age": 22, "sex": "M"}'
>>>

再转成字典类型

>>> info_dic = json.loads(info_str)
>>> info_dic
{'name': 'eclipse', 'age': 22, 'sex': 'M'}
>>> type(info_dic)
<class 'dict'>

格式化输出:

>>> json_dics2 = json.dumps(info_dic, sort_keys = True, indent = 4, separators = (',',':'))
>>> print(json_dics2)
{
    "age":22,
    "name":"eclipse",
    "sex":"M"
}
>>>

2. pickle 操作,通过二进制读写的方式操作一个类的写入,这很方便的操作一个对象。这里读临时文件的时候没有指定一个句柄,没法正常关闭文件。

>>> class Test:
...     def __init__(self, name, age):
...         self.name = name
...         self.age  = age
...
>>> f = open('./tmp.txt', 'wb')
>>> f.write(pickle.dumps(Test('eclipse', 22)))
67
>>> f.close()
>>> handler = pickle.loads(open('./tmp.txt', 'rb').read())
>>> handler.name
'eclipse'
>>> handler.age
22
>>> handler
<__main__.Test object at 0x000002436D8960B8>
>>>
上一篇 下一篇

猜你喜欢

热点阅读