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()

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.

commented: Nice short post +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.