Skip to content

Commit c5f3db1

Browse files
Add examples for converter and formatter
1 parent 176050d commit c5f3db1

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

Doc/library/csv.rst

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ The :mod:`!csv` module defines the following functions:
7373
in which case unquoted fields are transformed with the optional *converter* argument,
7474
or into floats if it is not given.
7575
*converter* is called as ``converter(index, field)``,
76-
where *index* is the 0-based position of the field in the row.
76+
where *index* is the 0-based position of the field in the row,
77+
so the conversion can depend on the column.
7778

7879
A short usage example::
7980

@@ -120,6 +121,7 @@ The :mod:`!csv` module defines the following functions:
120121
or with :func:`str` if it is not given.
121122
*formatter* is called as ``formatter(index, value)``,
122123
where *index* is the 0-based position of the field in the row,
124+
so the formatting can depend on the column,
123125
and must return a string.
124126
Quoting is still determined by the original value.
125127

@@ -730,6 +732,26 @@ done::
730732
for row in csv.reader(['one,two,three']):
731733
print(row)
732734

735+
Converting each column to its own type when reading::
736+
737+
import csv
738+
from decimal import Decimal
739+
types = [str, int, Decimal]
740+
with open('prices.csv', newline='') as f:
741+
reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC,
742+
converter=lambda index, field: types[index](field))
743+
for row in reader:
744+
print(row)
745+
746+
Writing the third column with two decimal places::
747+
748+
import csv
749+
def formatter(index, value):
750+
return format(value, '.2f') if index == 2 else str(value)
751+
with open('prices.csv', 'w', newline='') as f:
752+
writer = csv.writer(f, formatter=formatter)
753+
writer.writerows(someiterable)
754+
733755

734756
.. rubric:: Footnotes
735757

0 commit comments

Comments
 (0)