csv23 provides the unicode-based API of the Python 3 `csv` module for Python 2 and 3. It allows code to run under both versions of Python by abstracting the bytes vs. text differences and adhering to the newer unicode-based interface. The library defaults to UTF-8 encoding and addresses several known bugs in the standard library's `csv` module. The current version is 0.3.4, and it is primarily in maintenance mode for cross-Python 2/3 compatibility features.
pip install csv23Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `csv23.open_csv` as a context manager for both writing and reading CSV files, ensuring proper encoding handling. It also shows how to use `DictReader` to parse rows as dictionaries.
For Python 2 compatibility, pin to `csv23==0.3.4`. For new projects targeting only Python 3, `csv23` still offers useful wrappers but direct `csv` module use might suffice.
Always provide the `fieldnames` keyword argument when initializing `DictWriter` or `open_csv(..., rowtype='dict', mode='w', fieldnames=...)`.
If header names contain special characters (e.g., spaces, hyphens) which are invalid Python identifiers, pass `rename=True` to `open_csv` when `rowtype='namedtuple'` to automatically convert them to valid names (e.g., `_0`, `_1`).
Specify the correct `encoding` parameter when opening the file, e.g., `csv23.open_csv('file.csv', encoding='latin1')`. If unsure, try common encodings like 'latin1', 'cp1252', or use a library like `chardet` to detect it. You can also specify `errors='replace'` or `errors='ignore'` in the `open_csv` call to handle problematic characters.Provide a list of column headers as the `fieldnames` argument when creating the `DictWriter` or calling `open_csv`. For example: `with csv23.open_csv('output.csv', 'w', rowtype='dict', fieldnames=['Header1', 'Header2']) as writer:`.Use an 8-bit clean encoding like 'utf-8' (default) or 'latin-1' if possible. If a multi-byte encoding like 'utf-16' is truly required, you might need to handle the file opening with `io.open` or similar directly, then pass the file-like object to `csv23.reader`/`writer` (though this might bypass some `csv23` benefits).