import os.path def get_file(): '''Prompt for the name of an existing file, open the file for reading, and return the file object. As long as the user enters the name of a file that does not exist, print "File does not exist.", and prompt them for another name. ''' # Note: os.path.exists(filename) returns True if filename exists, # and False, otherwise def get_line(myfile): '''Read a line from open file myfile and return it, but with the new line character at the end of the line removed and all the characters in lower case.''' def create_dicts(pfile): '''Read in the data from the open picture data file, pfile, and return a tuple (pictures,faces,places,events), where the file format is as described in the assignment handout, and pictures, faces, places, and events are the data structures described in the assignment handout.''' # You definitely want to write a helper function, which you # call three times, once for each of the dictionaries faces, # places, events. This will save you lots of typing, and make # your code more readable. # Start by initializing pictures, faces, places, and events # Then, use a while loop to read lines from the files. You do # not want to use a for-loop, because you want to do different # things, depending on where you are in the file. For example, # when you have just read 'faces','events', or 'places' from the # file, you want to use a nested loop to read all of the faces, # etc. inside that section, stopping when you hit 'end'. # Hint: it would be helpful to define a variable, new_picture, # which is True whenever the line that was just read is the # name of a new picture, and False otherwise. You can test new_picture # to know when you should add a line to the list of pictures. # Here is the beginning of the while loop: line = get_line(pfile) while line != "": # inside the while loop, test what the current line is, and do # something appropriate # # This will take some thought, trying different things out, etc. # # Don't wait until the last minute! if __name__ == '__main__': # first time, use the file a3pdata1.txt pfile = get_file() (pictures,faces,places,events) = create_dicts(pfile) # now, print each of pictures, faces, places, and events in turn # see the sample output for the format # note that the dictionary entries are printed out in alphabetical # order of keys; your program should do that too. # Note: if ks is the list of keys of your dictionary, then # ks.sort() sorts them for you. # Note: if you write a function to print a dictionary, it will # save you lots of typing. # second time, use the file a3pdata2.txt pfile = get_file() (pictures,faces,places,events) = create_dicts(pfile) # again, print each of pictures, faces, places, and events in turn