Python将结果保存到文件并调用它们

2024-09-28 05:17:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个程序,它将存储学生id、姓名和D.O.B.s

该程序使用户能够删除、添加或查找学生。代码如下:

students={}

def add_student():
  #Lastname, Firstname
  name=raw_input("Enter Student's Name")
  #ID Number
  idnum=raw_input("Enter Student's ID Number")
  #D.O.B.
  bday=raw_input("Enter Student's Date of Birth")

  students[idnum]={'name':name, 'bday':bday}

def delete_student():
  idnum=raw_input("delete which student:")
  del students[idnum]
def find_student():
  print "Find" 
menu = {}
menu['1']="Add Student." 
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True: 
  options=menu.keys()
  options.sort()
  for entry in options: 
    print entry, menu[entry]

  selection=raw_input("Please Select:") 
  if selection =='1': 
    add_student()
  elif selection == '2': 
    delete_student()
  elif selection == '3':
    find_students 
  elif selection == '4': 
    break
  else: 
    print "Unknown Option Selected!" 

我遇到的问题是,当程序结束时,如何让程序将任何添加的记录保存到文件中。它还需要在程序重新启动时读回记录。在

我一直在网上找这类事情的教程,但是没有用。这就是我想添加的代码吗?公司名称:

^{pr2}$

我是Python新手,如果有任何帮助,我将不胜感激。非常感谢。在


Tags: name程序inputrawdefdeletestudentmenu
2条回答
import pickle,os
if os.path.exists("database.dat"):
    students = pickle.load(open("database.dat"))
else:
    students = {}
... #your program

def save():
    pickle.dump(students,open("database.dat","w"))

这取决于,如果要实际保存python对象,请签出PickleShelve,但如果只想输出到文本文件,请执行以下操作:

with open('nameOfYourSaveFile', 'w') as saveFile:
    #.write() does not automatically add a newline, like print does
    saveFile.write(myString + "\n")

这里有一个answer,它解释了要打开的不同参数,如ww+a,等等

例如,假设我们有:

^{pr2}$

要读回文件,我们需要:

names = []
numbers = []
emails = []

with open('nameOfYourSaveFile', 'r') as inFile:
    for line in inFile:
        #get rid of EOL
        line = line.rstrip()

        #random example
        names.append(line[0])
        numbers.append(line[1])
        emails.append(line[2])

        #Or another approach if we want to simply print each token on a newline
        for word in line:
            print word 

相关问题 更多 >

    热门问题