Example Creating a CSV File

The following is an example of writing a list to a CSV file. I assign some arbitrary mixed data (strings and numbers) to a list named data and write it to file. Try it yourself, and then open the created file test.csv to view the file contents.

>>> L = [['Time', 'Value', 'Notes'], [0, 20, 'Start point'],\ ... [0.1, 'Middle point'], [2]] >>> import csv

>>> f = open('../data/test.csv', 'wb') >>> csv.writer(f).writerows(L) >>> f.close()

Here are the contents of the test file, test.csv:

Time,Value,Notes 0,20,Start point 0.1,Middle point 2

Try changing the values of the list, such as adding a comma to one of the strings. Now, open the file in a spreadsheet application: did the application manage to read the comma properly? Open the file in a text editor and notice the string containing the comma is now quoted. The csv module took care of adding quotes as required. More about the csv module in Chapter 5.


So far we've used Python's csv module liberally. You might be wondering why we're not using the function split(V) instead of the csv.reader object. The answer is that the csv module also addresses special cases such as a string that includes a comma. Consider the following row:

"Surname, Name", 2008, 450

Module csv will handle this properly and return three elements. However, split(V) will return four elements: the quoted string will be broken in two.

Was this article helpful?

0 0

Post a comment