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.

Newsletter Email Twitter Facebook Google+ LinkedIn Github Stackoverflow More

This week in tutorial we covered file input.

A specific example of how to take a command line argument, and input the file into a list is below

import sys

filename = None

#Were there any extra command line arguments
if len(sys.argv) > 1:

    #if there were, place them into filename
    filename = sys.argv[1]
else:
    print "No File Specified" 

#Checked if we had a filename
if filename != None:
    #We are going to attempt to do something, specifically, open a file
    try:
        #Load the file that was specified into the variable aFile
        aFile = open(filename)

        #Get a list of each line
        lines = aFile.readlines()
        
        #Close the file
        aFile.close()

        #Remove the extra new line character from the end of the line
        for i in range(0,len(lines)):
            lines[i] = lines[i].rstrip("\n")

        #Print the list of lines from our file
        print lines
    #If we are unable to open the file, we want to know that it doesn't exist
    except IOError:
        print "The specified file doesn't exist"