#Leave the next line alone when solving this script! FILL_IN_THE_BLANK = "???" """ Fill In The Blank Exercise... There are five blanks below-- fill them in with what you've learned so far. Answers will be posted online. Hint: Take a look at the type of the variable called "FILL_IN_THE_BLANK"-- It's a string, which means that each of the blanks below should be filled with either a string literal ("somestring") or a string variable (something = "somestring"). When all blanks are filled in, the script will sort all the entries of the CSV based on date and print them into output.txt so that the date comes first in each row. """ import sys if len(sys.argv) != 2: print "expected exactly one argument, the csv file." #filen is the filename filen = sys.argv[1] #fileh is the file object (also called a file handle) try: fileh = open(filen, "r") except IOError: exit("the file '" + filen + "' doesn't exist.") outputh = open("output.txt", "w+") #collect the lines in a new dictionary to be sorted by the date field. #the key is a date in string form #the value is a list of entries that have that date entries = {} for lineno, line in enumerate(fileh): #the first line is a header describing what each column in the file means... #discard it. if lineno == 0: continue #newline characters are different in windows and non-windows #in windows, it's "\r\n" (two special characters) #everywhere else, it's "\n" #let's slice away the newline characters from this file #if the last two characters are "\r\n" if line[-2:] == "\r\n": #remove both characters from the line line = line[:-2] #else, if the second last character isn't "\r"... #check if the last character is "\n" and cleave it off. elif line[-1:] == "\n": line = line[:-1] else: exit("line" + str(lineno) + ":\n" +\ line +"\n" + "unexpected end of line character.") #we're expecting a CSV (comma-separated-value) file #the some_string.split() function can break each line into a list of #comma separated chunks #!!!!! BLANK #1 #the split method takes a single argument... #a separator string to break apart the larger string brokenline = line.split( "," ) #!!!!! Uncomment the next line to see what that would look like. # #print brokenline # #!!!!! #!!!!! BLANK #2 #we're sorting by something-- #conveniently, we will use this something as the key for our dictionary #of data row entries key = brokenline[-1] try: entries[key] except KeyError: #create a new list for this entry of the dictionary entries[key] = [] #BLANK #3 #we want to add lines of data to the list stored in entries[key] entries[key].append( brokenline ) else: #BLANK #4 #this is the same thing as the item above entries[key].append( brokenline ) for date in sorted(entries): #line is equal to a list of rows sharing the same key, the date. for line in entries[date]: #BLANK #5 #we want to print a row of data back out print >>outputh, date + ",", ", ".join(line[:-1])