Quote:
|
Originally Posted by somehollis
The program works exactly as it should. I've fixed all the bugs that I have found thus far... I'm just curious to see if the way I wrote this is the best (or good enough). Should I have done something differently? Is there unnecessary code?
|
There are a few things that could be done differently. Your file opening code for instance, could be more easily written thus:
try:
file = open("data.txt")
for line in file:
if line == "": break
values = line.split(',')
dbase[values[-2]] = values[:-2]
finally:
file.close() The "finally" clause makes sure that even if there is an IOError, the file will be closed correctly. This code may need to be wrapped in a further try-except statement in order to ignore any IOErrors.
In fact, one could make it simpler still, and use the standard csv module:
import csv
try:
file = open("data.txt", "rb")
for row in csv.reader(file):
if not row: break
dbase[rows[-2]] = rows[:-2]
finally:
file.close() One could also use csv.writer to write to the file in a similar manner.
The second thing I'd do differently would be to use a dictionary instead of a lot of elif-statements:
def add_person():
name = raw_input("Enter name:")
dbase[name] = []
...
choices = {
0 : add_person,
1 : add_item,
...
}
while choice != 9:
print menu
try:
choice = int(raw_input("Selection:"))
choices[choice]()
except ValueError:
print "Invalid choice: must be a number"
except KeyError:
print "Invalid choice: number must be from 0 to 9" The third thing I'd consider is whether the data can be saved in a different format. If data.txt is only read by this Python program, then it might be better to use the shelve module instead.
The shelve module allows you to tie a dictionary to a file, such that any chance to the dictionary, is automatically saved to the file. Thus, your file reading and writing code could be replaced by two lines:
import shelve
dbase = shelve.open("data.shf")