# 1. create a file called "friends.csv" # 2. gather the following information 5 friends: # name # email address # favorite cartoon (or movie) # for each friend, record the information in one line in friends.csv, # separate each piece of information with a comma (,) # 3. write a function to read the file # using open() and read() # 4. write a function to read the file # using open() and readlines() # 5. write a function to read the file # using open() and readline() # 6. write a function to read the file # using with open() # 7. write a function to read the file and # process the information # split the information into pieces (reminder, we have csv, thus split by a comma) # store the information in a dictionary, where # key is (friend) name # value is list containing email and cartoon, that is, [email, cartoon] # the function then returns the newly created dictionary file_name = 'friends.csv' def read_from_file(filename): infile = open(filename, 'r') # default mode: r # read the files's contents file_contents = infile.read() print(file_contents) infile.close() print("==== example: using read() ==== ") read_from_file(file_name) def readlines_from_file(filename): infile = open(filename, 'r') # read the files's contents file_contents = infile.readlines() print(file_contents) infile.close() print("==== example: using readlines() ==== ") read_from_file(file_name) def readline_from_file(filename): infile = open(filename, 'r') # read the first line line = infile.readline() # while there are more lines to read while line != "": print(line.rstrip()) # throws extra spaces at the end and print line line = infile.readline() # read a line infile.close() print("==== example: using readline() ==== ") readline_from_file(file_name) def read_file_with_open(filename): with open(filename) as infile: file_contents = infile.read() print(file_contents) print("==== example: using with open to open the file ==== ") read_file_with_open(file_name) def process_info(filename): friends_dict = {} infile = open(filename, 'r') # read the first line line = infile.readline().strip() # while there are more lines to read while line != "": pieces = line.split(',') if len(pieces) > 0: name = pieces[0] email = pieces[1] cartoon = pieces[2] friends_dict[name] = [email, cartoon] line = infile.readline().strip() # read a line infile.close() return friends_dict print("==== example: process info ==== ") print(process_info(file_name))