简体   繁体   English

使用Pickle保存字典-不起作用

[英]Using Pickle to save Dictionary— Not Working

I am currently making a game, where, at the end, the users Name and Experience points will be saved in a dictionary to a file. 我目前正在制作一个游戏,最后,用户的名称和体验点将在字典中保存到文件中。 Then, I will call the file and print out the Players with their names and respective experience. 然后,我将调用该文件并打印出播放器及其名称和各自的经验。

However, for some reason I am getting a "TypeError: must be str, not bytes" 但是,由于某种原因,我收到“ TypeError:必须为str,而不是字节”

I don't know how to work around this, to me my code looks accurate. 我不知道如何解决此问题,对我而言,我的代码看起来很准确。 What can I do to fix this error? 我该如何解决该错误?

code

import pickle
game_winners_tracker=open("C://Users//Documents//GameWinners.txt",   "a")

finalname=str(x.character_name)
finalexp=str(x.exp)

print(finalname)
print(finalexp)

dumping={finalname:finalexp}
pickle.dump(dumping,game_winners_tracker)
game_winners_tracker.close

game_winners_tracker_second=open("C://Users//Documents//GameWinners.txt", "rb")
names_scores=pickle.load(game_winners_tracker_second)
print(names_scores)
print("The End!")

Note 注意

When I call to print finalname and finalexp in the code above( it is just to test to see what is in x.character_name and x.exp) I get what I expect- 当我在上面的代码中调用print finalname和finalexp时(只是为了测试以查看x.character_name和x.exp中的内容),我得到了我所期望的-

IE it will print: IE浏览器将打印:

 Megan 130.5 

Which I convert both to strings so why am I getting a TypeError? 我将它们都转换为字符串,所以为什么会收到TypeError?

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); 模式“ r +”,“ w +”和“ a +”打开文件进行更新(读取和写入); note > that 'w+' truncates the file. 注意>“ w +”会截断文件。 Append 'b' to the mode to open the file in binary > mode, on systems that differentiate between binary and text files; 在区分二进制文件和文本文件的系统上,将'b'附加到模式以二进制>模式打开文件; on systems that don't have this distinction, adding the 'b' has no effect. 在没有此区别的系统上,添加“ b”无效。

From Python API Python API

So Try: 因此,请尝试:

import pickle
game_winners_tracker=open("C://Users//Documents//GameWinners.txt",   "ab")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM