# A CSV FILE IS A 2D GRID OF DATA. IT IS A VERY VERSATILE STORAGE FORMAT. # Within Python, this same structure is represented as a nested list. # Each sublist of the nested list represents a row from the csv file # The general process for using a csv file for storage with Python is: # 1) Use Python to open the file and read all data from it into a nested list # 2) Edit the data within the Python list according to need. # 3) Write the data back to the file again import csv # the csv library contains code for handling csv files. rows = [] # creates an empty list called "rows" # OPEN A CSV FILE CALLED mycsvfile.csv (or CREATE if it doesn't exist) AND WRITE TO IT ------------------------- with open('mycsvfile.csv', 'w', newline="") as csvfile: # "w" is for writing, # newline= ensures that each row written terminates correctly # the With statement will close the file as soon as everything indented is completed print("Adding contents to 'mycsvfile.csv' file...\n ") csv_file= csv.writer(csvfile) # uses the writer method csv_file.writerow (['Surname','First name','Date of Birth']) # writes the header row to the file using a list csv_file.writerow (['Smith', 'John', '11-Dec-2004']) # writes a data row to the file using a list csv_file.writerow (['Banana', 'Fred', '11-Jan-2000']) # writes a 2nd data row to the file using a list # writes multiple rows to the file using a nested list csv_file.writerows ([['Fishface', 'Carol', '11-Feb-2003'],['Picklechin', 'Peter', '16-Feb-2007']]) # READ FROM CSV FILE mycsvfile.csv AND PRINT OFF EACH ROW OF DATA ---------------- with open('mycsvfile.csv', 'r') as csvfile: # "r" is for reading csv_file= csv.reader(csvfile) # uses the reader method print("\nPrinting contents of 'mycsvfile.csv' file...\n") for row in csv_file: # for each row in the file print(row) # each row can be obtained as a list or.... print (', '.join(row)) # joins together individual data items on a row with ", " in between and prints them # READ FROM CSV FILE mycsvfile.csv AND PRINT OFF ALL ROWs OF DATA AS A LIST of LISTS ---------------- print("Putting 'mycsvfile.csv' file into a list...\n") with open('mycsvfile.csv', 'r') as csvfile: # uses the reader method rows = list(csv.reader(csvfile)) print(rows) print("Printing out the full list, list by list:\n") for row in rows: # for each row of data now stored in the list called "rows" print(row) # print each row # THE LIST rows IS A 2D ARRAY. ITEMS CAN BE ACCESSED USING TWO INDICES. FOR EXAMPLE... print("\nAccessing a single element from the list:\n") print(rows[1][1]) print("\nHere is an example:\n") print("First name: ", rows[1][1]) print("Surname: ", rows[1][0]) print("DOB: ", rows[1][2])