使用pickle将对象存储到文件中时出现 TypeError: write() argument must be str, not bytes

来源:互联网 发布:数据恢复免费版下载 编辑:程序博客网 时间:2024/06/03 14:03

pickle默认操作二进制文件,使用文件函数的时候需要注意,否则出现 TypeError

如下,open函数参数更改为 wb 可以正常运行

#!/usr/bin/python3# -*- coding: utf-8 -*-# 实现用户的历史记录功能# 使用容量为 n 的队列结构from collections import dequefrom random import randintimport pickleimport os# 队列的初始值,容量# history = deque([], 5)history = deque()if os.path.exists("./history"):  history = pickle.load(open("history", "rb"))else:  histoty = deque([], 5)# N = randint(0, 100)N = 60def guess(k):  if k == N:    print('Right')    return True  if k < N:    print(str(k) + " is less-than N")  else:    print(str(k) + " is greater-than N")  return Falsewhile True:  line = input('Please input a number: ')  if line.isdigit():    k = int(line)    history.append(k)    if guess(k):      break  elif line == 'history' or line == "h?":    print(list(history))pickle.dump(history, open("history", "wb"))
阅读全文
0 0
原创粉丝点击