© 2004-22

Reading CSV Data

Python comes equipped with a special CSV file handiling library
include it at the top of your code as shown in the snippet

Once your data has been read into the list you can access it as you would any two dimensional list with the syntax:

# Author: A Knifton
# Date: 6 Apr 2019
# Purpose: Read a CSV file and process line by line

import csv  # makes the csv commands available to this script

dataFile = open('StudentScores.csv')  # assign a file handler
dataReader = csv.reader(dataFile)  # assign the csv reader to the file handler
fileContent = list(dataReader)  # assign the file contents to a local variable before the file is closed

# good housekeeping

# fileContent can now be processed as a 2D list datatype in the normal way
for lineItem in fileContent:
    for item in lineItem:
        print(f"{item}", end=" ")
    print() # newline for each record