# Chapter8Modules.py # imports import csv # globals -> variables that will be used in the scope of this file filename = "orders.csv" # fieldnames ## orderID: int ## orderTotal: float ## orderProcessed: str -> Yes/No ## ccApproved: str Approved/Declined header = [ 'orderID', # int -> dbName.tblOrders.OrderID 'orderTotal', # float -> apiName.varName 'orderProcessed', # str -> Yes/No 'ccApproved' # str Approved/Declined ] # header # custom functions ## writeToCsv() ### filename ### fieldnames = header def write_to_csv( orderID, orderTotal, orderProcessed, ccApproved ): # 4 user inputs fieldnames = header # getting the header with open(filename, 'a', newline='') as file: # buffer buffer = csv.DictWriter(file, fieldnames=fieldnames) # do we need to write the header row if file.tell() == 0: buffer.writeheader() # attr named fieldnames for its values # write the order data buffer.writerow( { 'orderID': orderID, 'orderTotal': orderTotal, 'orderProcessed': orderProcessed, 'ccApproved': ccApproved } ) # buffer print(f"Order ID: {orderID} was added to the order file: {filename}.") ## readCsv() ### filename def read_from_csv(): with open(filename, 'r') as file: buffer = csv.DictReader(file) for row in buffer: dataRow = f"Order ID: {row['orderID']} Order Total: ${row['orderTotal']} Order Processed: {row['orderProcessed']} Approval Status: {row['ccApproved']}" print(dataRow) ''' Order ID: 45214 Order Total: $25.52 Order Processed: Yes Approval Status: Yes Order ID: 521445 Order Total: $52.25 Order Processed: Yes Approval Status: Approved Order ID: 52145 Order Total: $52.25 Order Processed: Yes Approval Status: Declined '''