[Tutor] Simple Python Address Book (Advice welcome!)
mariocatch
mariocatch at gmail.com
Sun Jun 17 03:45:19 CEST 2012
Hello All,
<Note: the below code only works on Windows as it currently writes a file
out to 'C:\temp\address.txt'. I also use Linux, but do most of my
development on Windows, sorry!, any advice still welcome!>
I'm currently in the midst of learning Python, and am absolutely loving the
language thus far! I'm a .NET developer in my professional life, and have
been recently influenced to learn Python - and I'm glad I was :)
I am working on an address book application (input through raw_input(),
nothing fancy) in the 2.7 redist.
I'm essentially asking if someone wouldn't mind taking a look at what I
have so far, and giving some advice on some of my weak areas, and areas
I've marked with comments on how to better approach some of my solutions
(in a more *Pythological* way :) ). I'm still familiarizing myself with
Python, and I would greatly appreciate anyone's help in this task of mine
:) Just a learning project for myself, one of many!
I'm not sure how you would like the code, I'll simply paste it here since I
imagine people are wear of opening attachments through email:
import re # email validation
import textwrap #wrapping text in raw_input (not sure if this is best way
to do this?)
# forward declarations
addressBookPath = r'C:\temp\addresses.txt'
addressBook = {} # address book held in memory before dumped to file
emailFormatRegex = r'(\w[\w]*)@([\w]+\.[\w]+)'
recordDelimiter = ' | ' # split name | email in file
def LoadAddresses():
""" Loads all addresses from file and places
them in tuple in form (bool, list), where the list is each
row from the file (a person's name | email). """
success, lines = (False, [])
try:
f = open(addressBookPath, 'r')
lines = f.readlines()
f.close()
success, lines = (True, lines)
except IOError as e:
print 'Error opening address book: ', e
return (success, lines)
def main():
(success, lines) = LoadAddresses()
if not success:
shouldMakeNewBook = raw_input(textwrap.fill("""You do not have an
address book yet.
Would you like to create
one?"""))
if shouldMakeNewBook in ('y', 'ye', 'yes'):
f = open(addressBookPath, 'w')
f.close()
print 'New address book created.', addressBookPath
else:
print 'Exiting...'
return
else:
# now that we have the file loaded into memory,
# fill out the addressbook from file
for line in lines:
splitStr = line.split(recordDelimiter)
addressBook[splitStr[0]] = splitStr[-1]
# main input loop (break with 'q' or 'quit' during input)
while True:
newPersonNameInput = raw_input('Enter new person\'s name: (q/quit
to stop):')
if newPersonNameInput.lower() in ('q', 'quit'):
break
addressBook[newPersonNameInput] = newPersonNameInput
while True: # loop until email is in valid format (x at y.z)
newPersonEmailInput = raw_input('Enter new person\'s email:
(q/quit to stop):')
match = re.search(emailFormatRegex, newPersonEmailInput)
if not match:
print 'email validation failed... try again.'
continue
else:
addressBook[newPersonNameInput] = newPersonEmailInput
break # success
RecordAddresses()
print addressBook
def RecordAddresses():
""" Writes out each address to the file in the form of name | email. """
f = open(addressBookPath, 'w')
for k, v in sorted(addressBook.items()):
#is there a better way to do this without placing a newline after
each row?
#it's causing multiple line separations when writing back out to
file (because each
# time we finish reading, it ends with a trailing newline).
f.write("{0}{1}{2}\n".format(k, recordDelimiter, v))
f.close()
if __name__ == '__main__':
main()
I appreciate any feedback!
-catch
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120616/f7325c75/attachment.html>
More information about the Tutor
mailing list