2013-11-03 33 views
1

好的,我知道这个话题已经被解决了好几次,但没有一个我看到的是帮助我。我在标题中遇到了错误,我不知道如何解决错误。这里是我的代码:ValueError:需要超过1个值才能解压

def loadRecords(): 
    f = open("stu.txt", "r") 
    students = f.readlines() 
    f.close() 
    return students 

def addStudent(): 
    n = input("Enter student's name: ") 
    ex1 = input("Enter Exam 1 grade: ") 
    ex2 = input("Enter Exam 2 grade: ") 
    ex3 = input("Enter Exam 3 grade: ") 
    return n + " " + ex1 + " " + ex2 + " " + ex3 + "\n" 

def displayStudents(students): 
    for record in students: 
     n, ex1, ex2, ex3 = record.split(",") 
     ex1 = int(ex1) 
     ex2 = int(ex2) 
     ex3 = int(ex3) 
     print("%-10s %5s %5s %5s" % (n, ex1, ex2, ex3)) 

def displayAvg(students): 
    n = 1 
    for record in students: 
     n, ex1, ex2, ex3 = record.split(",") 
     ex1 = int(ex1) 
     ex2 = int(ex2) 
     ex3 = int(ex3) 
     avg = (ex1 + ex2 + ex3)/3 
     print("%-10s %5s" % (n, round(avg, 1))) 
    n += 1 

def saveRecords(students): 
    f = open("stu.txt", "w") 
    f.writelines(students) 
    f.close 

def main(): 
    students = loadRecords() 

    while True: 
     print("""       
Program Options. 
    1.) Display all contacts 
    2.) Create new contact 
    3.) Display Averages 
    4.) Save and exit 
    """) 
     option = input("Enter 1, 2, or 3: ") 
     print() 

     if option == "1": 
      displayStudents(students) 
     elif option == "2": 
      newRecord = addStudent() 
      students.append(newRecord) 
     elif option == "3": 
      displayAvg(students) 
     elif option == "4": 
      saveRecords(students) 
      break 
     else: 
      print("Not happening") 

main() 

下面是收到错误:

Traceback (most recent call last): 
    File "C:/Python33/Program 4/pro4.py", line 65, in <module> 
    main() 
    File "C:/Python33/Program 4/pro4.py", line 53, in main 
    displayStudents(students) 
    File "C:/Python33/Program 4/pro4.py", line 16, in displayStudents 
    n, ex1, ex2, ex3 = record.split(",") 
ValueError: need more than 1 value to unpack 

下面是我使用的文件,如果你想运行的代码中使用记事本。

sam wilson,98,80,73 
sue green,92,98,74 
sue adams,89,89,92 
ron harris,90,87,100 
linda tyler,76,72,88 
dave smith,72,91,75 
steve davis,88,92,84 

回答

4

你可能有至少一个线在你的文件(通常是最后一行);明确地测试:

for record in students: 
    if not record.strip(): 
     continue 
    n, ex1, ex2, ex3 = record.split(",") 

你可能想看看csv module阅读你的学生记录,而不是;你仍然需要跳过空行,但逗号分割是为你处理的。

+0

好吧,那工作,直到我试图添加一个学生,然后查看文件 – user2899009

+0

@ user2899009:那是因为你不是用*空格*而不是写出学生,而不是逗号。 –

+0

@ user2899009:如果不清楚,Martijn的意思是因为你在文件中添加了空格而不是逗号分隔的记录。为了解决这个问题,只需要将'addStudent()'的最后一行改为'return','。join((n,ex1,ex2,ex3))''。 – martineau

相关问题