简体   繁体   中英

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"

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-

IE it will print:

 Megan 130.5 

Which I convert both to strings so why am I getting a TypeError?

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note > that 'w+' truncates the file. Append 'b' to the mode to open the file in binary > mode, on systems that differentiate between binary and text files; on systems that don't have this distinction, adding the 'b' has no effect.

From Python API

So Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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