Temporary Advertisements:
Ad
Ad
Ad
Python CSV: preserve quoted commas and multiline fields with DictReader
by nolookshot - Friday October 16, 2026 at 03:41 PM
#1
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:
 
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 newline

For 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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make a call attack for free Manfruity 21 3,112 1 hour ago
Last Post: tetegix230
  Read any book for free Manfruity 6 5,005 1 hour ago
Last Post: ad3tak
  Python argparse: why type=bool misreads False and how to make an on/off flag nolookshot 0 64 3 hours ago
Last Post: nolookshot
  Useful links for developers Manfruity 56 7,474 3 hours ago
Last Post: nolookshot
  ✅ HOW TO GET ANY STEAM GAME FOR FREE ✅ UHQ METHOD ✨ DECEMBER 2023 artikino 10 3,434 Yesterday, 03:38 PM
Last Post: Chjvimiiic

Forum Jump:


 Users browsing this forum: 5 Guest(s)