Python: How to write to a .csv file

Just like reading from .csv files, writing to .csv files also requires importing the csv module.

Python: How to open and read .csv documents

First define the path and name of your output file, then carefully build your output such that every line you want to write in the .csv file is a list with the same number of elements. For example, here is what the code should look like so far:

import csv

writepath = r'C:\Users\Chris\Desktop\python-blog\write_example.csv'

row1 = ['Sub region', 'Old QTR', 'New QTR', 'Difference', '% Change', 'Comments']
row2 = ['Traffic Direction Record', '6', '6', '0', 'n/a', 'n/a']
row3 = ['Traffic Event Record', '2523', '2523', '0', 'n/a', 'n/a']
row4 = ['Traffic Location Record', '34140', '38576', '4436', '12%', 'Increase']
row5 = ['Totals', '36669', '41105', '4436', '12%', 'Increase']

For the rest of this example I will use a try/except block, a ‘with open() as var’ construct, ‘wb’ as the second argument to the open() function, a csv.writer object with a comma as the delimiter:

try:
    with open(writepath, 'wb') as outfile:
        writer = csv.writer(outfile, delimiter = ",")

        # Note: You could just as easily use a control loop here to iterate
        # through all the rows you want to write.. The below example shows how to write
        # each row individually, without using iteration

        writer.writerow(row1)
        writer.writerow(row2)
        writer.writerow(row3)
        writer.writerow(row4)
        writer.writerow(row5)

except:
    print "Write Error: Permission denied. Can't open", writepath

print "Success! The file has been written here:", writepath

Running this script, I got this message on my screen:

Success! The file has been written here: C:\Users\Chris\Desktop\python-blog\write_example.csv

Then when I opened up the write_example.csv file in Excel, I see:

 

For more information about csv.writer(), see:
https://docs.python.org/2/library/csv.html