Python Csv

csv is a module that supports (de-)serializing CSV files.


Usage

DictReader


DictWriter


Reader

import csv

with open(file, 'r', newline='', encoding='latin-1') as f:
    r = csv.reader(f)
    for row in r:
        print(list(row))


Writer

import csv

data = [["John", "Doe", 123], ["Jane", "Doe", 456]]

with open(file, 'w', newline='', encoding='latin-1') as f:
    w = csv.writer(f)
    w.writerows(data)

Alternatively, write individual rows.

for row in data:
    w.writerow(data)


Constants

The above functions take one of the following constants as a quoting option. The ensuing behavior often depends on other options passed on those functions, such as quotechar.

Constant

Meaning

csv.QUOTE_ALL

quote all fields using the quotechar

csv.QUOTE_MINIMAL

quote fields which contain special characters (delimiter, quotechar, and lineterminator) using the quotechar

csv.QUOTE_NONNUMERIC

quote all non-numeric fields using the quotechar

csv.QUOTE_NONE

never quote fields; if delimiter is encountered in output, it is escaped with escapechar or csv.Error is raised

If csv.QUOTE_NONNUMERIC is passed to a reader, all unquoted fields are cast to float.

If csv.QUOTE_NONE is passed to a reader, all quotes are retained as part of a field's data.


See also

Python csv module documentation

Python Module of the Day article for csv


CategoryRicottone

Python/Csv (last edited 2023-10-13 14:14:53 by DominicRicottone)