# Chapter 7 # myCSVExample.py # imports import csv # Python Standard Module # globals filename = "contacts.csv" # define write() def write_to_csv(fname, lname): with open(filename,'a', newline='') as csvfile: col_Names = ['FirstName', 'LastName'] writer = csv.DictWriter(csvfile, fieldnames=col_Names) if csvfile.tell() == 0: writer.writeheader() # fieldnames=col_Names writer.writerow({'FirstName': fname, 'LastName': lname }) # define read() def read_from_csv(): with open(filename,'r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: data = f"First Name: {row['FirstName']} Last Name: {row['LastName']}" print(data) # bootstrap or init function Main Application def main(): try: while True: fname = input("Enter Contact First Name: ").title() lname = input("Enter Contact Last Name: ").title() write_to_csv(fname, lname) again = input("Do you want to add another contact? (yes/no: " ) if again.lower() != 'yes': #YES yes YEs yes break except Exception as err: print(f"{err}") finally: print("Thank you.") read_from_csv() # Which one of these 3 do we run at runtime? if __name__ == "__main__": main()