Python write() 参数必须是 str,而不是字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38524770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write() argument must be str, not bytes
提问by Austin Howard
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.
我是一名初学者程序员,正在为绝对初学者阅读 python 书。我在尝试为琐事游戏编写高分函数时遇到了问题。当函数 'highscore(user, highscore):' 被调用时,我尝试相应地分配参数,以便我可以将信息腌制到文件中以备后用。但是我在尝试转储所需信息时遇到错误。
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.
在 pickle.dump 部分是我产生错误的地方。我不断收到(如标题所示)写入参数错误。
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..
我不明白为什么它不将它们识别为字符串。当它们在主函数中定义时,它确实是一个字符串..
回答by Martijn Pieters
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:
看起来您正在阅读一本针对 Python 2 的书。您需要以二进制模式打开文件;添加b
到模式:
Hscore = open('highscore.txt', 'ab')
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.
如果您的书包含更多此类问题,那么可能是时候切换到支持 Python 3 的书或安装 Python 2.7 了,至少是为了完成本书的练习。