# Read # https://storage.googleapis.com/cs1111/practice/books.csv # from the Internet. Do not save to your computer # # Write the following functions # # 1. load_books(inventory, url) # - read the book inventory from a given url # - 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) import urllib.request def load_books(inventory, url): is_header = True stream = urllib.request.urlopen(url) for line in stream: if is_header: # get header header = line.decode('UTF-8').strip().split(',') for i in range(len(header)): header[i] = header[i].strip() is_header = False else: # get content book_info = {} columns = line.decode('UTF-8').strip().split(',') for i in range(1, len(columns)): book_info[header[i]] = columns[i].strip() inventory[columns[0].strip()] = book_info print(inventory) def print_inventory_to_file1(inventory, filename): # use with open() to open a file # use print() 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 # print(content, file=outfile) outfile.write(content + '\n') # 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 # def write_inventory_to_file2(inventory, filename): # use open() and close() # use write() for file writing url = "https://storage.googleapis.com/cs1111/practice/books.csv" book_inventory = {} load_books(book_inventory, url) # print_inventory_to_file1(book_inventory, "url_print_inventory1.csv") # print_inventory_to_file2(book_inventory, "url_print_inventory2.csv") # write_inventory_to_file1(book_inventory, "url_write_inventory1.csv") # write_inventory_to_file2(book_inventory, "url_write_inventory2.csv")