pickle问题,写入文件是乱码,读出来会报错
来源:2-7 如何实现用户的历史记录功能(最多n条)

慕少0241385
2017-08-25
我是这样子写的程序代码存入文件的信息是€ccollectionsdequeq ]q(K-KeK唓Rq.这样子的一串乱码然后读出来也会报错读出来我尝试过其他写法也会报错请问我应该怎样写代码来实现呢
写回答
1回答
-
读取时试一下
q = pickle.load(open('E:\english.txt', 'rb'))
下面是我自己试过的代码,测试过没什么问题,可以参考下(基于python 3.6)
# 实现用户的历史记录功能 from collections import deque from random import randint import pickle import os os.chdir(os.path.dirname(os.path.abspath(__file__))) N = randint(0, 100) history = deque([], 5) def guess(k): if k == N: print ("right") return True if k < N: print ("%s is less than N" % k) if k > N: print ("%s is greater than N" % k) 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 (history) elif line == "save game" or line == "save": with open('history', 'wb') as f: pickle.dump(history, f) with open('res', 'wb') as f: pickle.dump(N, f) print ("saved successfully!") elif line == "load game" or line == "load": with open('history', 'rb') as f: history = pickle.load(f) with open('res', 'rb') as f: N = pickle.load(f) print ("load successfully!") else: print ("no such command")
042017-12-24
相似问题