CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases that is widely used in financial industry or other data driven field. Here is a simple example about how a table can be represented by CSV:

Sort Order Common Name Formal Name Type
1 Afghanistan Islamic State of Afghanistan Independent State
2 Albania Republic of Albania Independent State
3 Algeria People’s Democratic Republic of Algeria Independent State


# equivalent to a table
Sort Order,Common Name,Formal Name,Type  
1,Afghanistan,Islamic State of Afghanistan,Independent State,  
2,Albania,Republic of Albania,Independent State,  
3,Algeria,People's Democratic Republic of Algeria,Independent State,

As a common tool for in same field, Python has a well support for CSV file, and it provides a module for efficiently handling them.

csv Module

csv module provides reader and writer objects for controlling read and write sequences. In this post, we will briefly introduce some useful functions to help reader get the idea about how to manipulate CSV format in Python

Reading a CSV File

csv.reader(csvfile, dialect='excel', **fmtparams)

This function returns a reader object which will iterate over lines in the given csvfile. Following code shows us how to print out the table in previous section.

1 import csv
2 	with open('data.csv', newline='') as csvfile:
3 		data_reader = csv.reader(csvfile, delimiter=',')
4 		for row in data_reader:
5 			print(row)

We will have each row within an array with items separated by commas.

['Sort Order', 'Common Name', 'Formal Name', 'Type']
['1', 'Afghanistan', 'Islamic State of Afghanistan', 'Independent State', '']
['2', 'Albania', 'Republic of Albania', 'Independent State', '']
['3', 'Algeria', "People's Democratic Republic of Algeria", 'Independent State', '']

Writing a CSV File

csv.writer(csvfile, dialect='excel', **fmtparams)

This function returns a writer object responsible for converting the user’s data into delimited strings on the given file-like object. Following code shows us how to store above arrays back to a CSV file.

1 import csv
2 	with open('data-out.csv', 'w', newline='') as csvfile:
3 		data_writer = csv.writer(csvfile, delimiter=',')
4 		for row in data: # each row is an array
5 			data_writer.writerow(row)
6 
7 		# or
8 		data_writer.writerows(data)
# data-out.csv
Sort Order,Common Name,Formal Name,Type
1,Afghanistan,Islamic State of Afghanistan,Independent State,
2,Albania,Republic of Albania,Independent State,
3,Algeria,People's Democratic Republic of Algeria,Independent State,

What do you think?

With the rapid development of NoSQL database, how will you compare CSV format with JSON?

Reference: Python 3.4.2 Documentation