def main():
infile = open("studentinfo.txt", "rt")
data = infile.read()
fName, lName, ID, year = data.split(",")
year = int(year)
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a coma: "))
# Prompt create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
grade_1, grade_2, grade_3 = grades
# Convert the grades to strings so they can be written to a new file
[grade_1, grade_2, grade_3] = [str(grade_1), str(grade_2), str(grade_3)]
# Calculate the average
average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0
# Convert the average to a string
average = str(average)
# Write the information to the file
outfile = open("studentreport.txt", "w")
outfile.write("*******Student Report*******\nStudent Name:" + fName + " " + lName)
outfile.write("\nStudent ID: " + converted_id + "\n" + "Username: " + uName + "\n\n")
outfile.write("Grade 1: " + str(grade_1) + "\n" "Grade 2: " + str(grade_2) + "\n" + "Grade 3: " + str(grade_3) + "\n" + "Average: " + str(average))
infile.close()
outfile.close()
main()
如何使用可读的文本文件使其正常运行 这是我运行程序帮助时得到的全部内容吗?
Enter the three test scores separated by a coma: 80,78,90,
>>> 80,78,90,
(80, 78, 90)
>>> main()
Enter the three test scores separated by a coma: 87,86,90
>>>
答案 0 :(得分:1)
可能存在一些语法问题,但我无法测试它,因为我没有您的文件,但这可能与您的想法一致:
def get_grades(student_name):
grades = raw_input("Enter the three test scores for {0} separated by a coma: ".format(student_name)).split(',')
if len(grades) != 3:
print "must enter three grades"
return get_grades(student_name)
return float(grades[0]), float(grades[1]), float(grades[2])
with open("studentreport.txt", "w") as outfile:
outfile.write("*******Student Report*******\n")
with open("studentinfo.txt", "r") as infile:
for student in infile:
fName, lName, ID, year = student.split(",")
year = int(year)
uName = "{0}{1}{2}".format(lName[:4], fName[:2], str(year)).lower()
converted_id = "{0}-{1}-{2}".format(ID[:3], ID[3:5], ID[5:])
# Prompt the user for three test scores
grade_1, grade_2, grade_3 = get_grades("{0} {1}".format(fName, lName))
average = sum([grade_1, grade_2, grade_3])/3
outfile.write("Student Name:{0} {1}\n".format(fName, lName))
outfile.write("Student ID: {0}\nUsername: {1}\n\n".format(converted_id, uName))
outfile.write("Grade 1: {0}\nGrade 2: {1}\nGrade 3: {2}\nAverage: {3}\n\n".format(grade_1, grade_2, grade_3,average))
用输入测试:
sam, snead, kghasjkdfiuaski21, 2006
john, doe, 9792345678872, 2009
garth, nroken, 097892364, 2006
输出:
*******Student Report*******
Student Name:sam snead
Student ID: kg-ha-sjkdfiuaski21
Username: snesa2006
Grade 1: 56.0
Grade 2: 67.0
Grade 3: 78.0
Average: 67.0
Student Name:john doe
Student ID: 97-92-345678872
Username: doejo2009
Grade 1: 67.0
Grade 2: 89.0
Grade 3: 78.0
Average: 78.0
Student Name:garth nroken
Student ID: 09-78-92364
Username: nroga2006
Grade 1: 45.0
Grade 2: 67.0
Grade 3: 89.0
Average: 67.0
请记住: Eval是邪恶的