4 hours ago
CSV records are not necessarily physical lines. A quoted cell can contain a comma or a newline, so split(',') and counting lines can both produce incorrect results.
This self-contained example uses only the standard library:
For a real UTF-8 file, open it with newline='' so the CSV parser handles line endings:
The reader returns strings; convert numeric columns explicitly. If the source format uses semicolons, pass delimiter=';' rather than replacing characters in the raw text. The list above is only for the tiny demonstration; iterate directly when processing a large file.
Reference: https://docs.python.org/3/library/csv.html
This self-contained example uses only the standard library:
import csv
from io import StringIO
sample = 'item,note\npencil,"blue, soft"\nnotebook,"two\nlines"\n'
rows = list(csv.DictReader(StringIO(sample, newline='')))
assert len(rows) == 2
assert rows[0]['note'] == 'blue, soft'
assert rows[1]['note'] == 'two\nlines'
print(len(rows)) # 2 records, despite the embedded newlineFor a real UTF-8 file, open it with newline='' so the CSV parser handles line endings:
with open('sample.csv', encoding='utf-8', newline='') as stream:
for row in csv.DictReader(stream):
print(row['item'])The reader returns strings; convert numeric columns explicitly. If the source format uses semicolons, pass delimiter=';' rather than replacing characters in the raw text. The list above is only for the tiny demonstration; iterate directly when processing a large file.
Reference: https://docs.python.org/3/library/csv.html
