Python基础 —— 使用 pickle 模块存储数据报错的解决办法

# 写入错误
TypeError: write() argument must be str, not bytes


# 读取错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 0: illegal multibyte sequence

解决方案:

def storeTree(inputTree, fielname):
    import pickle
    # 写文件时,注明 'wb'
    fw = open(fielname, 'wb')
    pickle.dump(inputTree, fw)
    fw.close()

def grabTree(filename):
    import pickle
     # 读文件时,注明 'rb'
    fr = open(filename, 'rb')
    fr = open(filename)
    return pickle.load(fr)

storeTree(myTree, 'classifierStorage.txt')
print(grabTree('classifierStorage.txt'))

输出:

{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

Process finished with exit code 0

你可能感兴趣的:(Python基础)