Python保存和读取对象的方法(基于自带的pickle模块)


"""
!python 3, pickle module achieves Persistent Stores. The saved file only for python.
refers to http://c.biancheng.net/view/5736.html

pickle module provides four methods:
- dump: serialize python object into binary and write it in a file.
- dumps: serialize python object into binary.
- load: read a file and deserialize binary into python object.
- loads: deserialize binary into python object.
"""

import pickle


def deserialize_binary(binary):
    t = pickle.loads(binary)  # b'\x80\x04\x95%\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x01a\x94Kd\x8c\x01b\x94\x8c\x03bba\x94\x8c\x01c\x94}\x94(h\x01Kdh\x02K\xc8uu.'
    print(t)
    print('read done!')
    return t


def get_data_from_json_file(filepath: str) -> {}:
    with open(filepath, 'rb') as f:
        data = pickle.load(f)
    print(data)  # the output could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
    '''output!'''
    for key in data.keys():
        print(f'{key}={data[key]}')
        # the output could be
        # a=100
        # b=bba
        # c={'a': 100, 'b': 200}
    print('read done!')


def serialize_python_object(content: {}):
    b = pickle.dumps(content)
    print(b)
    print('write done!')
    return b
    # the content could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
    # in the json file, it shows:
    # {
    #   "a": 100,
    #   "b": "bba",
    #   "c": {
    #       "a": 100,
    #       "b": 200
    #   }
    # }


def put_data_into_json_file(filepath: str, content: {}):
    with open(filepath, 'wb') as f:
        pickle.dump(content, f)
        # the content could be {'a': 100, 'b': 'bba', 'c': {'a': 100, 'b': 200}}
        # in the json file, it shows:
        # {
        #   "a": 100,
        #   "b": "bba",
        #   "c": {
        #       "a": 100,
        #       "b": 200
        #   }
        # }
    print('write done!')

在pycharm读取json文件时,显示如下: