# Working with data in files # contacts.csv # csv module is a Python Standard Module import csv # write rows to a csv def writeAllRows(new_contact): filePath = "c:/python/my_python/CONTACTS.csv" try: with open(filePath, 'a', newline='') as csvfile: # Create a csv writer csv_writer = csv.writer(csvfile) # Write the new data to the file csv_writer.writerow(new_contact) except Exception as err: print(err) finally: print("---End of writeAllRows ---") # read rows from csv def readAllRows(): filePath = "c:/python/my_python/CONTACTS.csv" # assign the csv file to a variable page 45 # f = open("CONTACTS.csv") # open the csv file using the with keyword with open(filePath, newline='') as csvFile: # with as keyword # Create a csv reader csv_reader = csv.reader(csvFile) # Read the header row using next() # open a file the "next" row IS the first row headerRow = next(csv_reader) # reads the next line # headerRow[0] FIRSTNAME # headerRow[1] LASTNAME # headerRow[2] ZIPCODE # data rows "row" "dataRow" for dataRow in csv_reader: # Access the headerRows col firstName = headerRow[0] lastName = headerRow[1] zipCode = headerRow[2] #Access the dataRows col data_firstName = dataRow[0] data_lastName = dataRow[1] data_zipCode = dataRow[2] print("Contact First Name:", data_firstName) print("Contact Last Name:", data_lastName) print("Contact Zip Code:", data_zipCode) print("-------------------------------")