我需要在單個def中創建一個程序,打開一個文本文件「成績」,其中第一個,最後一個和成績由逗號分隔。每一行都是一個單獨的學生。然後顯示學生和成績以及班級平均水平。然後繼續添加另一個學生並將其保存到文本文件中,同時包括舊學生。 我想我只是不明白python通過文本文件的方式。如果我將'行'註釋掉,我會看到它會打印old_names,但它好像一切都沒有了。當行沒有被註釋掉'old_names'沒有被打印,這讓我認爲文件被關閉了?還是空的?但是一切仍然在txt文件中,因爲它應該是。文本文件讀寫ValueError:需要超過1個值才能打包
目前我得到這個錯誤....這一點我敢肯定,告訴我,我是弱智有在「行」沒有信息
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
謝謝您的解釋,我可能需要再讀幾遍,但我明白了。現在,如果我可以讓文件在文本文件中寫入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 – Krill 2014-10-03 00:49:21
用.join()再次修復。 – Krill 2014-10-03 01:55:53