csv.writer, csv.reader
csv.writer(csvfile, dialect='excel', **fmtparams)
csv.reader(csvfile, dialect='excel', **fmtparams)Write and read CSV rows. Open the file with newline=''. Values written as integers are still read back as strings.
| Parameter | Description |
|---|---|
csvfile | A file-like object. For a real file, open it with newline='' as required by the official documentation. |
dialect | A registered dialect name or a dialect object. The default is excel. |
Returns: writer returns a writer object with writerow and writerows. reader returns an iterator of rows, each a list of strings.
- A field that contains a comma is quoted, as in "Grace, Hopper".
- path.read_bytes() shows the dialect's \r\n terminators. Text mode without newline='' would translate those endings on some platforms, which is why the official guidance is to use newline=''.
- The integer 2 is written in the second column, but the reader returns the string '2'. The csv module does not infer int or float.
import csv
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "rows.csv"
with path.open("w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "count"])
writer.writerow(["Ada", 2])
writer.writerow(["Grace, Hopper", 3])
with path.open("r", newline="") as file:
print(repr(file.read()))
file.seek(0)
rows = list(csv.reader(file))
print(rows)
print(type(rows[1][1]).__name__, rows[1][1])Expected output
'name,count\r\nAda,2\r\n"Grace, Hopper",3\r\n'
[['name', 'count'], ['Ada', '2'], ['Grace, Hopper', '3']]
str 2