csv.field_size_limit
A safety net against runaway fields (e.g. an unclosed quote swallowing the rest of a file). The limit is module-wide, counts characters, and applies to reading only.
Demo
import csv old = csv.field_size_limit(5) try: rows = list(csv.reader(['abcde,xy'])) finally: csv.field_size_limit(old) (old, rows)
The limit counts the characters of the field value: "abcde" fits a limit of 5, "abcdef" raises _csv.Error: field larger than field limit (5). The surrounding quotes of "abc" are not part of the value, so a limit of 3 is enough. With 0 no field may have even one character, but empty fields are still fine. The snippet restores the old limit in finally because the setting is shared by the whole program.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| new_limit | int | no | The new maximum number of characters per field. Omit it to only read the current value. |
Return value
int — The limit that was in force before the call.
Common patterns
import csv, sys limit = sys.maxsize while True: try: csv.field_size_limit(limit) break except OverflowError: limit //= 2
import csv old = csv.field_size_limit(10_000_000) try: rows = list(csv.reader(f)) finally: csv.field_size_limit(old)
Examples
Pitfalls
import csv lines = ['a,"b'] + ['x' * 100] * 2000 len(next(csv.reader(lines)))
import csv lines = ['a,"b'] + ['x' * 100] * 10 try: next(csv.reader(lines, strict=True)) except csv.Error as e: msg = str(e) msg
When to use
- Files with legitimately huge fields (embedded documents, base64 blobs)
- Hiding broken quoting — check the data first (strict=True helps)
Notes
FAQ
First check for an unclosed quote. If the fields really are that large, raise the limit before reading: csv.field_size_limit(10_000_000) (or the largest value your platform accepts).