1

I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.

The program gives the user the ability to remove, add, or find a student. Here is the code:

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

The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.

I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:

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

I'm new to Python so any help would be appreciated. Thanks so much.

mleko
  • 11,650
  • 6
  • 50
  • 71
Jack
  • 191
  • 1
  • 2
  • 7

2 Answers2

3

It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:

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

Here's an answer that explains the different arguments to open, as in w, w+, a, etc.

As an example, say we have:

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

To read the file back, we do:

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 
Community
  • 1
  • 1
Steve P.
  • 14,489
  • 8
  • 42
  • 72
  • So would I just add that to the end of the code? I tried and it gave me an error in regards to the "mystring" saying it was undefined. – Jack Dec 03 '13 at 00:05
  • @Jack `myString` means nothing, it's just a varialbe name that I made up, that's supposed to represent a string. – Steve P. Dec 03 '13 at 00:07
  • I'm sorry haha. I sort of figured as much. I'm new to Python so everything is still very basic to me. Do you know if this will work on the Repl.it site? I'm required to use that to create codes. – Jack Dec 03 '13 at 00:09
  • @Jack I added an example. – Steve P. Dec 03 '13 at 00:09
  • @Jack No idea, but this is perfectly valid, normal python code, as is `Pickle` and `Shelve`. – Steve P. Dec 03 '13 at 00:10
  • The Code now works with no errors. I'm sorry to keep pestering you, but do you know if there's a way to "read the records back" when the program starts again? – Jack Dec 03 '13 at 00:14
  • @Jack Yes, it depends on the format that you use to write them to the file. Check out my example (updated). – Steve P. Dec 03 '13 at 00:21
  • Everything seems to be working now! I just have to fix part of my earlier code, but the main problem I was having is solved thank you!! – Jack Dec 03 '13 at 00:38
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"))
squirl
  • 1,636
  • 1
  • 16
  • 30
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • it should be fine I had a typo with students being misspelled first... if you get an error post what the error is ... – Joran Beasley Dec 02 '13 at 23:39
  • I added the the code and it says there's an error with line 4. SyntaxError: invalid syntax. – Jack Dec 02 '13 at 23:41
  • well first of all it should be students since thats what you are messing with in your functions ... I still dont see a syntax error here – Joran Beasley Dec 02 '13 at 23:43
  • It wouldn't have to do with the fact I'm using the repl.it site to make the code would it? – Jack Dec 02 '13 at 23:47
  • Ok, I went in an retyped everything. Now it says the Error is that "IOError: [Errno 2] No such file or directory: 'database.dat' " – Jack Dec 02 '13 at 23:56
  • Is it possible by any chance that you named your program as pickle.py in which case the import will pick up your program and not the pickle module. – Ketan Maheshwari Dec 03 '13 at 00:14