Hello,
I'm doing (post) #2 of 'Projects for the Beginner' and I used for making this the 'The Address Book Revisited' example on this page The author says he even put in two errors on purpose. I have re-written the code and changed it more to a Code Library like program, but I have a problem with reading the file correctly into the dictionary.
So the problem is in the function readLib(lib), the for-construction is not correct used.
I have included the code below.
Visitors are free to use my code, but it's not 100% good (yet).
# A Code library
# Projects for the Beginner #2
# www.daniweb.com/forums/post159477-2.html
# Python 2.5 tested Begjinner 31jan2008
def readLib(lib):
import os
filename = 'codelib.txt'
if os.path.exists(filename):
store = file(filename, 'r')
for line in store:
key = line.strip()
value = line.strip()
lib[key] = value
else:
store = file(filename,'w')
store.close()
def saveLib(lib):
store = file("codelib.txt",'w')
for key,value in lib.items():
store.write(key + '\n')
store.write(value + '\n')
store.close()
def getOption(menu):
print menu
option = int(raw_input("Select an option(1-4): "))
return option
def addEntry(lib):
key = raw_input("Enter a name: ")
value = raw_input("Enter the code: ")
lib[key] = value
def removeEntry(lib):
key = raw_input("Enter a name to be deleted: ")
del (lib[key])
def findEntry(lib):
key = raw_input("Enter a name: ")
if key in lib.keys():
print key, lib[key]
else: print "Sorry, no entry for: ", key
def main():
theMenu = '''
----------- MENU -----------
1) Add code
2) Remove code
3) Find code
4)Quit and save
'''
theLib = {}
readLib(theLib)
option = getOption(theMenu)
while option != 4:
if option == 1:
addEntry(theLib)
elif option == 2:
removeEntry(theLib)
elif option == 3:
findEntry(theLib)
else: print "Invalid option, try again"
option = getOption(theMenu)
saveLib(theLib)
main()
*to run, save as a .py file and double click it.