Masthead

Writing To CSV Files Using the Python CSV library (Optional)

1. Introduction

Below is a description of how to use the python "csv" library to write CSV files. I have found this library very useful for reading CSV files but have had problems using it to write CSV files.

2. Writing a CSV file

The code below first opens the file for writing and then creates a csv "writer". The options passed to this writer are critical to allowing other applications to read your CSV files. The default is setup for UNIX machines which have different characters for terminating a line. Also, the default does not put quotes around strings which can lead to a wide variety of problems. The "QUOTE_NONNUMERIC" option addresses this by putting quotes on all values that are not numeric.

import csv

TheFile=open('C:/Temp/Test12.csv', 'w') # open the file for writing

# Create a CSV writer object
writer = csv.writer(TheFile,quoting=csv.QUOTE_NONNUMERIC, lineterminator = '\n') # just quote non-numbers and use "newline" for the end of line character

# write out each row of the CSV file.
writer.writerow(['SN', 'Person', 'DOB']) # write the header line
writer.writerow([1, 'John', '18/1/1997']) # specify the rows as lists
writer.writerow([2, 'Marie','19/2/1998'])

# close the file
TheFile.close()

 

Additional Resources

Python Documentation: Files

© Copyright 2018 HSU - All rights reserved.