backports.csv
backports.csv provides a backport of the Python 3 `csv` module to Python 2 environments. It addresses the significant API differences, particularly concerning string handling and native Unicode support, between Python 2 and Python 3's `csv` modules. The library is currently at version 1.0.7, with its last release on March 10, 2019, suggesting a maintenance-only cadence due to its Python 2 focus.
Common errors
-
ImportError: cannot import name csv from backports
cause Attempting to import `csv` directly from `backports` as if `backports` itself were the module `csv`, or trying `from backports.csv import csv` which isn't the correct access pattern.fixThe correct way to get the `csv` module functionality is `from backports import csv`. This makes the backported module available under the `csv` name. -
UnicodeEncodeError: 'ascii' codec can't encode character...
cause Attempting to write non-ASCII characters without specifying a proper encoding when opening the file, or not using `io.open` with `encoding='utf-8'` (or similar).fixEnsure files are opened with `io.open` and an explicit encoding, e.g., `with io.open(filename, 'w', newline='', encoding='utf-8') as f:`. -
TypeError: 'str' does not support the buffer interface (or similar encoding-related TypeErrors)
cause Mixing binary and text modes, or attempting to pass Python 2 `str` (byte strings) to `csv` operations when the backport expects Unicode strings, or vice-versa due to incorrect file opening.fixAlways use `io.open` with `newline=''` and a specific `encoding` to ensure the `csv` module receives and returns Unicode strings, as it expects Python 3-like text streams.
Warnings
- breaking The API of the `csv` module in Python 2 (native) is fundamentally different from that in Python 3. This library provides the Python 3 API, meaning code written for Python 2's native `csv` will break if migrated to use `backports.csv` without adaptation.
- gotcha Proper encoding and newline handling are critical when working with `backports.csv` in Python 2. Unlike Python 2's native `open`, `io.open` must be used with `newline=''` and an explicit `encoding` (e.g., 'utf-8') to correctly handle universal newlines and Unicode characters.
Install
-
pip install backports.csv
Imports
- csv
import backports.csv
from backports import csv
Quickstart
import io
from backports import csv
# Example: Reading a CSV file
def read_csv_file(filename):
rows = []
with io.open(filename, newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
rows.append(row)
return rows
# Example: Writing to a CSV file
def write_csv_file(filename, data):
with io.open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
# To make it runnable for demonstration, create a dummy file
dummy_data = [['Header1', 'Header2'], ['Value1', 'Value2'], ['Unicode test', '你好']]
write_csv_file('test.csv', dummy_data)
read_data = read_csv_file('test.csv')
print(read_data)