2016-02-03 123 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