Skip to content

Instantly share code, notes, and snippets.

@IanMcT
Created September 29, 2016 09:38
Show Gist options
  • Save IanMcT/3924b9a92e2671a0bef68edd8a9a41e3 to your computer and use it in GitHub Desktop.
Save IanMcT/3924b9a92e2671a0bef68edd8a9a41e3 to your computer and use it in GitHub Desktop.
Example program that uses a dictionary object and reads and writes to a binary file.
import pickle #used to serialize the data
import os.path
#Comment this code
#global variables
songs_and_bands = {"Drive": "Judge Jackson"}
def open_file():
global songs_and_bands #get global variable
if os.path.isfile('songs_and_bands.dat'):
binary_file=open('songs_and_bands.dat','rb')
songs_and_bands=pickle.load(binary_file)
binary_file.close()
def close_file():
global songs_and_bands #get global variable
binary_file=open('songs_and_bands.dat','wb')
pickle._dump(songs_and_bands, binary_file)
binary_file.close()
def list_bands():
global songs_and_bands
for keys in sorted(songs_and_bands.keys()):
print(keys,songs_and_bands[keys])
def find_a_song():
global songs_and_bands
s = input("What song are you trying to find?\n ")
if s in songs_and_bands:
print(s,songs_and_bands[s])
else:
print("Sorry, couldn't find the song.")
def delete_a_song():
global songs_and_bands
s = input("What song do you want to delete?\n ")
if s in songs_and_bands:
del songs_and_bands[s]
def add_a_song():
global songs_and_bands
song = input("Enter a song: ")
band = input("Enter a band: ")
songs_and_bands[song] = band
def main():
open_file()
user_input = input("Enter a choice: "
"1 - list bands "
"2 - Find a song "
"3 - Delete a song "
"4 - Add a song "
"5 - Exit \n")
while user_input != "5":
if user_input == "1":
list_bands()
elif user_input == "2":
find_a_song()
elif user_input == "3":
delete_a_song()
elif user_input == "4":
add_a_song()
elif user_input == "5":
break
else:
print("Choice needs to be 1-5")
user_input = input("Enter a choice: "
"1 - list bands "
"2 - Find a song "
"3 - Delete a song "
"4 - Add a song "
"5 - Exit \n")
close_file()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment