【问题标题】:text file reading and writing, ValueError: need more than 1 value to unpack文本文件读写,ValueError: need more than 1 value to unpack
【发布时间】:2014-10-02 17:49:18
【问题描述】:

我需要在单个 def 中创建一个程序,打开一个文本文件“等级”,其中第一、最后和等级用逗号分隔。每行是一个单独的学生。然后它显示学生和成绩以及班级平均水平。然后继续添加另一个学生和成绩并将其保存到文本文件中,同时包括旧学生。 我想我只是不明白 python 通过文本文件的方式。如果我注释掉“行”,我会看到它打印出 old_names 但它好像一切都消失了。当没有注释掉行时,没有打印'old_names',这让我认为文件已关闭?还是空的?但是所有内容仍然在 txt 文件中。

目前我收到此错误....我很确定这是在告诉我我智障“行”中没有信息

File "D:\Dropbox\Dropbox\1Python\Batch Processinga\grades.py", line 45, in main
    first_name[i], last_name[i], grades[i] = line.split(',')
ValueError: need more than 1 value to unpack

最终目标是让它给我当前学生的姓名和平均成绩。然后添加一名学生,将该学生和成绩保存到文件中。然后能够与包括新学生在内的所有学生一起恢复文件,然后重新开始。 我很抱歉成为一个小人。

def main():
    #Declare variables
    #List of strings: first_name, last_name
    first_name = []
    last_name = []
    #List of floats: grades
    grades = []
    #Float grade_avg, new_grade
    grade_avg = new_grade = 0.0
    #string new_student
    new_student = ''


    #Intro
    print("Program displays information from a text file to")
    print("display student first name, last name, grade and")
    print("class average then allows user to enter another")
    print("student.\t")

    #Open file “grades.txt” for reading
    infile = open("grades.txt","r")

    lines = infile.readlines()

    old_names = infile.read()
    print(old_names)

    #Write for loop for each line creating a list
    for i in len(lines):
         #read in line
         line = infile.readline()

         #Split data
         first_name[i], last_name[i], grades[i] = line.split(',')

         #convert grades to floats
         grades[i] = float(grades[i])

    print(first_name, last_name, grades)
    #close the file
    infile.close()

    #perform calculations for average
    grade_avg = float(sum(grades)/len(grades))


    #display results
    print("Name\t\t Grade")
    print("----------------------")
    for n in range(5):
        print(first_name[n], last_name[n], "\t", grades[n])

    print('')
    print('Average Grade:\t% 0.1f'%grade_avg)

    #Prompt user for input of new student and grade
    new_student = input('Please enter the First and Last name of new student:\n').title()
    new_grade = eval(input("Please enter {}'s grade:".format(new_student)))

    #Write new student and grade to grades.txt in same format as other records
    new_student = new_student.split()
    new_student = str(new_student[1] + ',' + new_student[0] + ',' + str(new_grade))

    outfile = open("grades.txt","w")

    print(old_names, new_student ,file=outfile)

    outfile.close()enter code here

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    Python 中的文件对象有一个“文件指针”,它跟踪您已经从文件中读取的数据。当您致电 readreadlinereadlines 时,它使用它来知道从哪里开始查找。调用readlines 将文件指针一直移动到文件末尾;随后的读取调用将返回一个空字符串。这解释了为什么您会在 line.split(',') 行上收到 ValueError。 line 是一个空字符串,因此 line.split(",") 返回一个长度为 0 的列表,但您需要一个长度为 3 的列表来执行您正在尝试的三重赋值。

    一旦获得lines 列表,您就无需再与infile 对象交互。你已经拥有了所有的台词;您也可以直接遍历它们。

    #Write for loop for each line creating a list
    for line in lines:
        columns = line.split(",")
        first_name.append(columns[0])
        last_name.append(columns[1])
        grades.append(float(columns[2]))
    

    请注意,我使用的是append 而不是listName[i] = whatever。这是必要的,因为当您尝试分配一个尚不存在的索引时,Python 列表不会自动调整大小。你只会得到一个IndexError。另一方面,append 将根据需要调整列表大小。

    【讨论】:

    • 谢谢,您的解释很到位,我可能需要再读几遍,但我明白了。现在,如果我可以让文件在文本文件中写入 old_names,它们是怎样的,而不是这样......['Mickey,Mouse,90\n', 'Jane,Doe,50\n', 'Minnie ,Mouse,95\n', 'Donald,Duck,80\n', 'Daffy,Duck,70\n'] Lars,Olrich,69
    猜你喜欢
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多