2016-02-03 229 views
-1

這是我的代碼,但不能用pickle加載它後,也認爲這是相當低效,謝謝。 寫入文件:Python字典酸洗

import pickle 

cont="yes" 
u_ele_stu={} 
ele_pl_stu={} 
x=len(u_ele_stu) 
y=len(ele_pl_stu) 

with open("Tennis Scores.txt" ,"wb") as a: 
while cont=="yes": 
    age=input("Would you like to add to under 11 list or 11-16? (under 11/11-16)") 
    if age=="under 11": 
     name=input("Input the name of a student: ") 
     pos=str(input("Input the last position they achieved in a tournament")) 
     u_ele_stu[x+1]=name, " ", pos 
    elif age=="11-16": 
     name=input("Input the name of a student: ") 
     pos=str(input("Input the last position they achieved in a tournament")) 
     ele_pl_stu[y+1]=name, " ", pos 
    cont=input("Would you like to add another student? yes/no") 
    cont.lower() 
if cont!="yes": 
    pickle.dump(u_ele_stu, a) 
    pickle.dump(ele_pl_stu, a) 

讀取文件:

import pickle 

with open("Tennis Scores.txt", "r") as a: 
    b=pickle.load(a) 
    c=pickle.load(a) 
    print(b) 
    print(c) 
+0

你確定你的縮進是正確的? – erip

+0

也不要在文件名中使用空格。或者至少逃離空間。 – erip

+0

你認爲它比較低效嗎? – msw

回答

0

嘗試在一個單獨的文件傾倒每個對象:

with open('u_ele_stu.txt', 'wb') as f: 
    pickle.dump(u_ele_stu, f) 

with open('ele_pl_stu.txt', 'wb') as f: 
    pickle.dump(ele_pl_stu, f) 
0

我通過添加B固定的問題在「r 「,我不認爲這是最有效的方式,但它只是比較...

與開放( 「網球Scores.txt」, 「R b」)爲:

+0

就是這樣。你編寫二進制數據,所以你必須讀取二進制數據。 – Matthias