2015-05-06 37 views
0

我目前正在做一個遊戲,最後,用戶名和經驗點將保存在一個字典中的文件。然後,我會打電話給這個文件,並用他們的名字和經驗打印出玩家。使用泡菜保存字典 - 不工作

但是,由於某種原因,我得到一個「類型錯誤:必須海峽,而不是字節」

我不知道如何解決這個問題,對我來說我的代碼看起來準確。我能做些什麼來解決這個錯誤?

代碼

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!") 

注意

當我打電話打印finalname和finalexp在上面的代碼(這是隻是爲了測試,看看有什麼是x.character_name和X。 exp)我得到了我所期望的 -

IE將打印:

Megan 
130.5 

我將它們都轉換爲字符串,爲什麼我會得到一個TypeError?

+6

你無需打開'B' –

+1

在這行沒你的錯誤? –

回答

2

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.

Python API

所以嘗試:

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