存储输入的信息 - Python

时间:2014-01-11 11:21:33

标签: python file collections external

最近我一直在用Python练习,并提出了一个简单的脚本,允许学生与他们的成绩一起输入。但是,我希望能够将输入的信息保存到外部.txt文件中,但我不知道如何执行此操作。

继承我的代码:

results = []

print ("\n")
print ("=============================================================================")
print ("\n")
Institution = str(input("Please Enter the Name of Your Institution: "))

while True:
   print ("\n")
   print ("---------------------------------NEW STUDENT---------------------------------")
   print ("\n")
   print ("Please Enter the Current Year of the Students Course")
   Year = int(input("(For Example, Year '1 / 2 / 3 / 4'): "))
   print ("\n")
   print ("-----------------------------------------------------------------------------")
   print ("\n")
   Student = str(input("Student Full Name: "))
   print ("\n")
   ID = int(input("Student ID Number: "))
   print ("\n")
   print ("-----------------------------------------------------------------------------")
   print ("\n")
   Grade1 = int(input("Enter Student's First Term Grade: "))
   Grade2 = int(input("Enter Student's Second Term Grade: "))
   Grade3 = int(input("Enter Student's Third Term Grade: "))
   Grade4 = int(input("Enter Student's Fourth Term Grade: "))

   average =  (Grade1+Grade2+Grade3+Grade4)/4

   print ("\n")
   print ("-----------------------------------------------------------------------------")
   print ("\n")
   print ("Total Grade Average: %G" % (average))

   passed_or_failed = "PASSED"
   if average < 40:
     passed_or_failed = 'FAILED'
   results.append(passed_or_failed)

   print ("\n")
   print ("%s has: %s" % (Student, passed_or_failed))
   print ("\n")

  cont = input('Do you want to keep entering students? Y/N: ')

   if cont.lower() == "n":
      print ("\n")
      print ("----------------------------------------------------------------------------")
      print ("\n")
      print ("Thank you for using FinalGrade. Goodbye.")
      break

这有可能吗?我被告知使用集合写入文件但是我发现很难弄清楚如何做到这一点。

谢谢

2 个答案:

答案 0 :(得分:1)

你可以使用:

with open('name_of_the_txt_file.txt','a') as fp: 
    fp.write("%s has: %s  " % (Student,passed_or_failed))

更多信息: http://docs.python.org/3.3/tutorial/inputoutput.html 7.2

答案 1 :(得分:0)

将您的数据整理为命名元组的字典 来自集合导入namedtuple

Student = namedtuple('Student', "id grades")
students = dict()
< get your data here>
student[<student name>] = Student(id, [grades])

然后您可以保存学生并使用简单的json module作为对象还原 - 只需使用转储加载调用< / p>