write()参数必须是str,而不是字节 [英] write() argument must be str, not bytes
问题描述
我是一名初学者程序员,并且正在为绝对初学者编写python书.我在尝试为琐事游戏编写高得分功能时遇到了一个问题.当函数'highscore(user,highscore):'被调用时,我尝试相应地分配参数,以便将信息腌制到文件中以备后用.但是我在尝试转储所需信息时遇到错误.
I'm a beginner programmer and am working through the book python for the absolute beginner. I have come across a problem trying to write a high scoring function for the trivia game. when the function 'highscore(user, highscore):' is called on I try to assign the arguments accordingly so I can pickle the information to a file for later use. however I am running into an error trying to dump the info needed.
def highscore(user, highscore):
'''stores the players score to a file.'''
import pickle, shelve
user = ''
highscore = 0
#Hscore = shelve.open('highscore.dat', 'c')
Hscore = open('highscore.txt', 'a')
pickle.dump(user, Hscore)
pickle.dump(highscore, Hscore)
#Hscore.sync()
Hscore.close()
由于我正在阅读本书,并且也看到了实际使用中的书架,因此我也尝试使用它们,但遇到了自己的一系列错误.因此请暂时忽略#".
since I'm working through the book and have also seen shelves in action I tried using them too but run into their own set of errors. so ignore the '#'s at this time.
是我正在生成错误的地方.我不断收到(如标题所示)写入参数错误.
at the part pickle.dump is where I'm generating an error. I keep getting (as the title suggests) a write argument error.
我不明白为什么它不能将它们识别为字符串.就像在主函数中定义它们时一样,它的确是字符串.
I don't understand why its not recognizing them as string. as when they are defined in the main function it is indeed a string..
推荐答案
您似乎正在研究一本针对Python 2的书.您需要以 binary模式打开文件;将b
添加到模式:
Looks like you are working through a book aimed at Python 2. You need to open your file in binary mode; add b
to the mode:
Hscore = open('highscore.txt', 'ab')
如果您的书中包含更多此类问题,那么可能至少是为了完成本书练习而切换到支持Python 3的书或安装Python 2.7的时候.
If your book contains more issues like these, it may be time to switch to one that supports Python 3 or to install Python 2.7 at least for the purposes of completing the book exercises.
这篇关于write()参数必须是str,而不是字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!