10-16-2026, 02:39 PM
A CSV record is not always one physical line: a quoted field can contain a comma or a newline. Splitting text with split(",") or splitting all lines before parsing can break valid records.
This single-line Python example uses only the standard library and synthetic data:
Expected output:
For a real UTF-8 file, the following is also one Python line. It counts parsed records, including the header, without collecting the whole file in a list:
Import csv first, as in the example above. Opening with newline="" lets the CSV parser handle line endings. Set delimiter and quotechar to match the producer if it uses a different dialect. Reader fields are strings by default; convert numeric columns explicitly after parsing.
Reference: https://docs.python.org/3/library/csv.html
This single-line Python example uses only the standard library and synthetic data:
import csv, io; rows = list(csv.reader(io.StringIO('item,note\nwidget,"line one\nline two"\ngadget,"a,b"\n', newline=""))); print(len(rows), repr(rows[1][1]), repr(rows[2][1]))Expected output:
3 'line one\nline two' 'a,b'For a real UTF-8 file, the following is also one Python line. It counts parsed records, including the header, without collecting the whole file in a list:
with open("example.csv", encoding="utf-8", newline="") as stream: print(sum(1 for row in csv.reader(stream)))Import csv first, as in the example above. Opening with newline="" lets the CSV parser handle line endings. Set delimiter and quotechar to match the producer if it uses a different dialect. Reader fields are strings by default; convert numeric columns explicitly after parsing.
Reference: https://docs.python.org/3/library/csv.html
