Jamie Starke bio photo

Jamie Starke

I develop for my career, but I also develop for fun, and whenever I think it can solve a problem I'm having. This has lead me to create side projects, such as Rental Map and BusTimes, among others.

Consulting Newsletter Email LinkedIn Github Stackoverflow More

This is a useful example of how to use Try/Excepts in Python

import sys

# Description: Loads a file into a list of lines
#
# Parameters: parameter 1 is the name of the file that I want to load
#
# Return: A list containing elements which are each single line from the file
def loadLines(filename):

    # Open the file with the name Filename.  If this file doesn't exist
    # the except statement in my main() function will catch it
    aFile = open(filename)

    # Create a new list where I will add the lines from the file 
    lines = []

    # Grab a single line from the file
    line = aFile.readline()

    # While the line is not blank (blank signifies the end of the file)
    while line != '':
        # Add this line to my list, removing the new line character at the end
        lines.append(line.rstrip())
        # Grab the next line from the file
        line = aFile.readline()

    # Once I finished reading, close the file
    aFile.close()

    # Return the list of lines in the file
    return lines


# This is the very high level of my program that will run all of the smaller pieces of my program
def main():
    try:
        filename = sys.argv[1] # Try to take the argument from the command line
        lines = loadLines(filename) # Load the file into a list of lines
        print lines # Print the lines to screen
    
    # If the argument from the command line is not there, inform the user of proper 
    # Syntax for running my program
    except IndexError: 
        sys.stderr.write("Please provide a filename.  Proper format 'python try-except.py [filename]'\n")
    # If the specified file doesn't exist, inform the user
    except IOError:
        sys.stderr.write("The specified File does not exist\n")
main()