0
点赞
收藏
分享

微信扫一扫

Python序列化json和pickle

十里一走马 2021-09-28 阅读 59

目录

  • 初识序列化与反序列化
  • 可序列化的数据类型
  • Python中的json
  • Python中的pickle

初识序列化

可序列化的数据类型

  • number、str、list、tuple、dict
  • 类、函数、集合无法进行序列化

Python的json模块

Python的pickle模块

实战

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     : 2021/8/23 20:56
# @Author   : InsaneLoafer
# @File     : package_json.py

import json

def read(path):
    with open(path, 'r') as f:
        data = f.read()
    return json.loads(data)

def write(path, data):
    with open(path, 'w', encoding='utf-8') as f:
        if isinstance(data, dict):
            _data = json.dumps(data)
            f.write(_data)
        else:
            raise TypeError('data is dict')
    return True

data = {'name':'insane', 'age':18, 'top':178}

if __name__ == '__main__':
    write('test.json', data)
    result = read('test.json')
    print(result, type(result))
    result['sex'] = 'boy'
    write('test.json', result)
    print(result)
  • test.json文件
{"name": "insane", "age": 18, "top": 178, "sex": "boy"}
{'name': 'insane', 'age': 18, 'top': 178} <class 'dict'>
{'name': 'insane', 'age': 18, 'top': 178, 'sex': 'boy'}

Process finished with exit code 0
举报

相关推荐

0 条评论