Python pickles不存储数据

时间:2017-12-11 05:35:09

标签: python pickle saving-data storing-data

我正在尝试通过Python创建一个带有pickles的注册器系统。我已经让系统记录用户输入,但它不会保存它以用于程序的未来实现。

以下是启动该程序的代码:

import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *

prompt = "Please select an option: \n 1  Create a new course \n 2  Schedule a new course offering \n 3  List this school's course catalogue \n 4  List this school's course schedule \n 5  Hire an instructor \n 6  Assign an instructor to a course \n 7  Enroll a student \n 8  Register a student for a course \n 9  List this school's enrolled students \n 10  List the students that are registered for a course \n 11  Submit a student's grade \n 12  Get student records \n 13 Exit"

farewell = "Thank you for using the Universal University Registrar System.  Goodbye!"

print ("Welcome to the Universal University Registration System.")

print ("\n")

try: #As long as CTRL-C has not been pressed, or 13 not been input by user.

  input_invalid = True
  while input_invalid:
    inst = input("Please enter the name of your institution. ").strip()
    domain = input("Please enter the domain. ").strip().lower()
    if inst == "" or domain == "":
      print("Your entry is invalid.  Try again.")
    else:
      input_invalid = False

  schoolie = Institution(inst, domain)

  if Path(inst + '.pkl').exists() == False:
    with open(inst + '.pkl', 'r+b') as iptschool:
      schoolie = pck.load(iptschool)

  while True:
    print (prompt)
    user_input = input("Please enter your choice:  ") 
    try:
      user_input = int(user_input)
      if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
        raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
    except ValueError:
      print("Not a valid number.  Please try again.")

    if user_input == 1: #Create a new course
      input_invalid2 = True #Ensure that the user actually provides the input.
      while input_invalid2:
        input_name = input("Please enter a course name:  ").strip()
        input_department = input("Please enter the course's department:  ").strip()
        input_number = input("Please enter the course's number (just the number, not the departmental prefix):  ").strip()
        try:
          input_number = int(input_number)
        except ValueError:
          print ("Please print an integer. Try again.")
        input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer:  ").strip()
        try:
          input_credits = int(input_credits)
        except ValueError:
          print ("Please print an integer. Try again.")

        if input_name != "" and input_department != "" and input_number and input_credits:
          input_invalid2 = False #Valid input
        else:
          print("One or more of your entries is invalid.  Try again.")

      added_course = Course(input_name, input_department, input_number, input_credits)
      for course in schoolie.course_catalog:
        if course.department == input_department and course.number == input_number and course.name == input_name:
          print("That course is already in the system.  Try again.")
          input_invalid2 == True
      if input_invalid2 == False:
        schoolie.add_course(added_course)
        print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))

这是第二个选项,它应该显示存储它,但它不存储。

elif user_input == 2: #Schedule a course offering
      input_invalid2 = True #Ensure that the user actually provides the input.
      while input_invalid2:
        input_department = input("Please input the course's department: ").strip()
        input_number = input("Please input the course's number: ").strip()
        course = None
        courseFound = False
        for c in schoolie.course_catalog:
          if c.department == input_department and c.number == input_number: #Course found in records
            courseFound = True
            course = c
            input_section_number = input("Please enter a section number for this course offering:  ").strip()
            input_instructor = input("If you would like, please enter an instructor for this course offering:  ").strip()
            input_year = input("Please enter a year for this course offering:  ").strip()
            input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER:  ").strip().upper()
            if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
              if input_instructor != "": #Instructor to be added later, if user chooses option 6.
                added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
              else:
                added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
              schoolie.add_course_offering(added_course_offering)
              input_invalid2 = False #Valid input
              print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
            else:
              print("One or more of your entries is invalid.  Try again.")
        if courseFound == False: #If course has not been found at the end of the loop:
          print("The course is not in our system.  Please create it before you add an offering.")
          break

顺便说一句,我认为我的系统正常关闭了。如果我错了,请纠正我:

   elif user_input == 13: #Exit
      with open(inst + '.pkl', 'wb') as output:
        pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
      del schoolie
      print (farewell)
      sys.exit()

except KeyboardInterrupt: #user pushes Ctrl-C to end the program
  print(farewell)

我认为我设置pickles文件的方式有问题。我正在创建它们,但我似乎没有将数据放入其中。

我为这个问题的冗长性质道歉,但我希望细节能帮助你理解我一直存在的问题。在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

似乎你可能有转储和负载逆转:(来自文档)

wxWidgets

答案 1 :(得分:0)

使用所有这些代码行,它确实会让人感到有些困惑,但我没有看到任何代码将pickle和对象写入文件。

在其他任何事情之前,您应该将文件分配给变量,以便您可以引用它。为此,您将拥有与此类似的代码:MyFile = open("FileName.extension","wb")MyFile可以是您想要的任何名称,它将是您稍后用于引用该文件的名称。 FileName是文件本身的名称。这是它在文件资源管理器中的名称。 .extension是文件的扩展名,指定文件类型。 您应该使用.dat wb是文件访问模式。 “w”表示写入,“b”表示二进制。 (腌制对象只能存储在二进制文件中。)

要编写pickle对象,您需要以下代码:pck.dump(object,MyFile)。 (通常,您会使用pickle.dump(object,MyFile),但导入了pickle as pck。)

将数据写入文件后,您将需要检索它。为此,MyFile的“wb”实例需要像这样关闭:MyFile.close()。然后,您需要使用以下代码以读取模式重新打开文件:MyFile = open("FileName.extension","rb")然后您将使用此object = pickle.load(MyFile)来读取数据。在上面的示例中,(load函数),您的object 必须与使用dump函数腌制时的名称相同。 (pck.dump(object,MyFile)

最后,你最终会得到类似的东西:

if writing conditions are true:
    MyFile = open("FileName.dat","wb")
    pickle.dump(object,MyFile)    # This will be repeated for each object.
    MyFile.close()

if reading conditions are true:
    MyFile = open("FileName.dat","rb")
    object = pickle.load(MyFile)    # This will be repeated for each object.
    MyFile.close()

如果这不是您想要的答案,我很抱歉。由于所有这些代码行,有点难以理解。我需要澄清以提供更好的答案。