954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Exception to ensure raw input in specific format

I'm creating a program that carrys out certain things dependent on the user input. One function is to read text from a text file, another is to add text to the same text file. I'm unsure about how to add an exception handler to make sure the text input is in the right format,

The text file contains a list of people with their birthdays in the form

Mike,Dec,25
John,Apr,13

and I don't know what I would put around my code to add text, in order to not crash the program when text isn't entered in this format.

Any help is much appreciated.

print "You chose to add a new birthday"
        file = open("birthdays.txt", "r")
        filedata = file.read()
        
        newLine = raw_input("Enter the name and birthday: ")
        file = open("birthdays.txt", "a")
        file.seek(0)
        file.write(newLine + "\n")
        file.close()
scott_liddle
Newbie Poster
4 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

You just have to describe the format to python. You are looking for 3 items separated by a comma. The third item is a digit and the second item is a 3 letter month.

*Note: Code is untested

print "You chose to add a new birthday"
with open('birthdays.txt', 'r') as readobj:
   filedata = readobj.read()
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun',
         'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
newLine = raw_input("Enter the name and birthday: ")
try:
   name, month, day = [x.strip(' \t\n') for x in newLine.split(',')]
   assert day.isdigit()
   assert month.lower() in months
   with open('birthdays.txt', 'a') as writeobj:
      writeobj.write(newLine + '\n')
except (AssertionError, ValueError):
   print 'Enter the information in Name, MM, DD format'

Also seek(0) doesn't work with the file opened in append mode. It always adds it to the end of the file.

ihatehippies
Junior Poster
190 posts since Oct 2008
Reputation Points: 33
Solved Threads: 13
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: