【发布时间】: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