banner

© 2004-21 ict4u.net

Reading & Appending CSV Data

This code demos how to read and append data to a CSV File

NOTE: If the file does not exists before updating, Python will automatically create one for you

Click hereto download the data file used in this code
# Author: A Knifton
# Date: 11 Dec 2017
# Purpose: Demo how to read and update a CSV text file

import csv

# initialise variables
newData = [['Harry',129], ['Xavier',132]] # data to be written to the file
dataFile = "players.csv" # file to be used

def updateCSV(CSVFile,dataList):
    # open the file in append mode with a newline character added to each line
    #  encoding="utf-8" - can be omitted
    myFile = open(CSVFile, 'a+', newline="\n") #set a file handler to manage the I/O
    myFileWriter = csv.writer(myFile) # Use the writer method to convert the data  into a CSV format
    for dataRow in dataList:
        myFileWriter.writerow(dataRow) # write a row of data to the file
    myFile.close()

def getCSVData(csvFile):
    csvList = []
    myFile = open(csvFile,)  # assign a file handler
    csvData = myFile.read().splitlines()  # read all the data into a list, split on newline
    for row in csvData:
        row = row.split(",") # now split each field on a comma
        csvList.append(row)
    myFile.close()
    return csvList

# read the data in the file before updating
playerData = getCSVData(dataFile)
print("Data BEFORE appending new records")
for player in (playerData):
    print(player)


# Add the data to the file
updateCSV(dataFile, newData)

# Check to see that the data has been added
playerData = getCSVData(dataFile)
print("\nData AFTER appending new records")
for player in (playerData):
    print(player)