# Download books.csv file from # https://storage.googleapis.com/cs1111/practice/books.csv # and save it in your computer # # Write the following functions # # 1. load_books(inventory, filename) # - read the book inventory from a given file # - record the book information in an inventory dict # in the following format, for example: # {'Intro to Python': # {'year': 2020, 'price': 60, 'quantity': 85}, # 'Python - banana': # {'year': 2018, 'price': 64, 'quantity': 100}, # 'Python Master': # {'year': 2018, 'price': 70, 'quantity': 59}, # 'Python crash course': # {'year': 2016, 'price': 40, 'quantity': 29}} # - you may assume the inventory dict is initially empty # # 2. write_inventory(inventory, filename) # - write book information from the inventory dict # to a given file name # (you may format the output file as you wish) def load_books(inventory, filename): with open(filename) as infile: # get header line line = infile.readline().strip() headers = line.split(',') for i in range(len(headers)): headers[i] = headers[i].strip() print('headers = ', headers) # get content line = infile.readline().strip() book_info = {} while line != '': # continue reading as long as the line has something columns = line.split(',') for i in range(1, len(columns)): book_info[headers[i]] = columns[i].strip() book_inventory[columns[0].strip()] = book_info line = infile.readline().strip() # get the next line print('load =', book_inventory) def print_inventory_to_file1(inventory, filename): with open(filename, "w") as outfile: # must use "w" mode for title, book_info in inventory.items(): line = title + " " for k_info, v_info in book_info.items(): line += v_info # print() takes any data type, must specify an output file print(line, file=outfile) def print_inventory_to_file2(inventory, filename): outfile = open(filename, "w") # must use "w" mode for title, book_info in inventory.items(): line = title + " " for k_info, v_info in book_info.items(): line += v_info # print() takes any data type, must specify an output file print(line, file=outfile) outfile.close() def write_inventory_to_file1(inventory, filename): with open(filename, "w") as outfile: # must use "w" mode for title, book_info in inventory.items(): line = title + " " for k_info, v_info in book_info.items(): line += v_info # write() takes string, need to add \n outfile.write(line + '\n') def write_inventory_to_file2(inventory, filename): outfile = open(filename, "w") # must use "w" mode for title, book_info in inventory.items(): line = title + " " for k_info, v_info in book_info.items(): line += v_info # write() takes string, need to add \n outfile.write(line + '\n') outfile.close() book_inventory = {} load_books(book_inventory, "books.csv") print_inventory_to_file1(book_inventory, "print_inventory1.csv") print_inventory_to_file2(book_inventory, "print_inventory2.csv") write_inventory_to_file1(book_inventory, "write_inventory1.csv") write_inventory_to_file2(book_inventory, "write_inventory2.csv")