Python-将结果保存到文件并回顾它们

时间:2013-12-02 23:25:29

标签: python save

我正在用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!" 

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

我一直试图在网上找到这类东西的教程,但无济于事。这是我想要添加的代码吗?:

f = open("myfile.txt", "a")

我是Python的新手,所以任何帮助都会受到赞赏。非常感谢。

2 个答案:

答案 0 :(得分:2)

这取决于,如果您想要实际保存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等。

举个例子,我们说:

with open('nameOfYourSaveFile', 'w') as saveFile:
    for i in xrange(10):
         saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")

要回读文件,我们会这样做:

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 

答案 1 :(得分:1)

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"))