The csv module can be used to work with data exported from spreadsheets and databases into text files formatted with fields and records, commonly referred to as comma-separated value (CSV) format because commas are often used to separate the fields in a record.

writing


In [2]:
import csv
import sys

unicode_chars = 'å∫ç'

with open('data.csv', 'wt') as f:
    writer = csv.writer(f)
    writer.writerow(('Title 1', 'Title 2', 'Title 3', 'Title 4'))
    for i in range(3):
        row = (
            i + 1,
            chr(ord('a') + i),
            '08/{:02d}/07'.format(i + 1),
            unicode_chars[i],
        )
        writer.writerow(row)

print(open("data.csv", 'rt').read())


Title 1,Title 2,Title 3,Title 4
1,a,08/01/07,å
2,b,08/02/07,∫
3,c,08/03/07,ç

reading


In [3]:
import csv
import sys

with open('data.csv', 'rt') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)


['Title 1', 'Title 2', 'Title 3', 'Title 4']
['1', 'a', '08/01/07', 'å']
['2', 'b', '08/02/07', '∫']
['3', 'c', '08/03/07', 'ç']

Dialect


In [4]:
import csv

print(csv.list_dialects())


['excel', 'excel-tab', 'unix']

Creating Dialect


In [6]:
import csv

csv.register_dialect('pipes', delimiter='|')

with open('testdata.pipes', 'r') as f:
    reader = csv.reader(f, dialect='pipes')
    for row in reader:
        print(row)


['Title 1 ', ' "Title 2" ', ' "Title 3"']
['1 ', ' "first line"']
['second line ', ' 08/18/17']