banner

© 2004-19 ict4u.net

Reading & Writing CSV Data

This code demos how to read and write CSV data

ImportantWhen writing CSV data using the methods from the CSV module, be aware that it uses \r \n
This adds an extra line feed to the data. You have to use the csv Dialect as show in this example to get the result you were expecting

Click hereto download the data file used in this code
## Author: A Knifton
# Date: 12 Mar 2018
# Purpose: read and write a CSV file


import csv  # makes the csv commands available to this script
csv.register_dialect('myDialect',  lineterminator = '\n') #make sure that only line feed is used

dataFile = "gameScores.csv"
newFile = "gamesscore revised.csv"

def getCSVData(csvFile):
    csvHandle = open(csvFile, "r")  # assign a file handler
    csvData = csv.reader(csvHandle ) # assign the csv reader to the file handler
    csvList = list(csvData)  # Use the list function to separate the data items
    csvHandle.close()

    return csvList

def writeCSVData(listData):

    with open(newFile, 'w') as csvFile:
        writer = csv.writer(csvFile ,dialect='myDialect' ) # use the dialect to only add a newline character rather
        # than the default return and newline
        writer.writerows(listData) # iterate through the list with writerows

        csvFile.close() # cleanup


listData = getCSVData(dataFile)
writeCSVData(listData)