# Chapter7.py # orders.csv # imports import csv import Chapter11Mod # global attr # Properties # List of orders with orderID, orderSubTotal, orderShipping, orderTotal, orderStatus, orderShipVia # Add 3 example orders to your list, not using user inputs orders = [ [1234, 50, 10, 60, True, "FedEx"], [1235, 50.50, 10, 60.50, True, "FedEx"], [1236, 50.75, 10, 60.75, False, "UPS"] ] # orders # Use a try block to write the orders to a csv file, catching all IOErrors if the file throws an exception. Write a header row to row 1 of the csv file. def export_orders_to_csv(orders): try: # pass # 2 common modes to open an IO file ## 'w' write mode: override all data in a file ## 'a' append mode: append the data to the end of the file ## default 'r' read mode # "c:/data/" absolute os specific windows/linux/mac # "../../data" relative os specific windows/linux/mac filename = "orders.csv" with open(filename,mode='w', newline='') as file: # define a variable for write to the file # write variable depends on the type of file # csv file import csv writer = csv.writer(file) writer.writerow(["orderid","ordersubtotal","ordershipping","ordertotal","orderstatus","ordershipvia"]) # try to avoid spaces in field names for order in orders: writer.writerow(order) print(f"Orders successfully exported to {filename}") # Page Redirect Error redirect = "fail" if redirect == "fail": Chapter11Mod.log_error("999", "Redirect Error after orders.csv export.") # Chapter 8 Page 238 except IOError as err: print(f"An error occurred: {err}.") except Exception as err: print(f"An error occurred: {err}.") finally: print("Thank you for using my application.") # Read data from a source file def read_orders_from_csv(): try: # Ask the user what file to read from # If the user enters an invalid file, throw IOError file not found filename = input("Enter the filename: ") with open(filename, mode='r') as file: reader = csv.reader(file) # skip the header row next(reader) # Create an empty list object for orders orders = [] for row in reader: # Read from reader directly print(row) # Append to List Object orders.append(row) # append an order to the orders list # orders = [ # [order1], # [order2] # ] print(orders) # [ [], [], [] ] except IOError as err: print(f"An error occurred: {err}")