使用pickle將對象存儲到文件中時出現 TypeError: write() argument must be str, not bytes

pickle默認操作二進制文件,使用文件函數的時候需要注意,否則出現 TypeError

如下,open函數參數更改爲 wb 可以正常運行

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# 實現用戶的歷史記錄功能
# 使用容量爲 n 的隊列結構

from collections import deque
from random import randint
import pickle
import 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 = 60

def 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 False

while 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"))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章