# 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): # you should practice using # with open(filename, mode) as file # file = open(filename, mode) and file.close() infile = open(filename, 'r') line = infile.readline().strip() # get header headers = line.split(',') for i in range(len(headers)): headers[i] = headers[i].strip() print(headers) line = infile.readline().strip() # get the first line book_info = {} while line != '': columns = line.split(',') for i in range(1, len(columns)): columns[i] = columns[i].strip() book_info[headers[i]] = columns[i] inventory[columns[0]] = book_info line = infile.readline().strip() print(inventory) infile.close() def print_inventory_to_file1(inventory, filename): # use with open() to open a file # use print() for file writing # outfile = open(filename, 'w') with open(filename, 'w') as outfile: for title, book_info in inventory.items(): content = title + " " for k,v in book_info.items(): content += v print(content, file=outfile) # def print_inventory_to_file2(inventory, filename): # use open() and close() # use print() for file writing def write_inventory_to_file1(inventory, filename): # use with open to open a file # use write() for file writing with open(filename, 'w') as outfile: for title, book_info in inventory.items(): content = title + " " for k, v in book_info.items(): content += v outfile.write(content + '\n') # must be string # def write_inventory_to_file2(inventory, filename): # use open() and close() # use write() for file writing 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") #