Search notes:

Python standard library: csv

The csv module allows to read and write CSV files.
A script to read a csv file line by line:
import csv

csv_file   = open('data.csv', 'r')
csv_reader = csv.reader(csv_file)

header = next(csv_reader)

for record in csv_reader:

    print('Record:')

    i = 0
    for rec_value in record:
        print('  ' + header[i] + ': ' + rec_value)
        i += 1
Github repository about-python, path: /standard-library/csv/script.py
The read csv file could be:
col 1,col 2,col 3
foo,bar,baz
one,two,three
42,,0
Github repository about-python, path: /standard-library/csv/data.csv

Methods and properties

import csv
for e in sorted(dir(csv), key=lambda s: s.lower()): print(e)
__all__
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
__spec__
__version__
_Dialect
Dialect A class that specifies how different aspects of CSV files, such as double quotes, white spaces, delimiters etc.
DictReader Returns an object similar to that returned by reader, but the CSV data can be accessed using a dict, i. e. with the names of the CSV columns.
DictWriter
Error
excel
excel_tab
field_size_limit
get_dialect
list_dialects
QUOTE_ALL
QUOTE_MINIMAL
QUOTE_NONE
QUOTE_NONNUMERIC
re
reader Returns an object which will iterate over the lines produced by any object that supports the iterator protocol (such as file or list objects). Compare with writer.
register_dialect
Sniffer
StringIO Compare with io.StringIO
unix_dialect
unregister_dialect
writer Creates an object that converts data into delimited strings and sends them to any object that has a write() method.

Read tab separated values

Sometimes, the fields are not separated by commas but rather by tabulators. This can be indicated with the delimiter argument:
import csv

csv_file   = open('data.tsv', 'r')
csv_reader = csv.reader(csv_file, delimiter="\t")

header = next(csv_reader)

for record in csv_reader:

    print('Record:')

    i = 0
    for rec_value in record:
        print('  ' + header[i] + ': ' + rec_value)
        i += 1
Github repository about-python, path: /standard-library/csv/read_tab_seperated_values.py
the file being read might look like
col 1	col 2	col 3
foo	bar	baz
one	two	three
42		0
Github repository about-python, path: /standard-library/csv/data.tsv

See also

Poor man's CSV reader
standard library

Index