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

Closing Excel

If you spend a lot of time wrting CSV files, you'll probably open them in Excel periodically to see what is in the file. Then, if you try to over write the file, it will not work because Excel does not allow files to be overriden that is has open. The following Python code will close Excel for you and can be put at the top of your code to make sure Excel is closed.

import os
os.system('taskkill /IM excel.exe')

Additional Resources

Python Documentation: Files

© Copyright 2018 HSU - All rights reserved.