backports.csv

1.0.7 · maintenance · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

The quickstart demonstrates reading and writing CSV data using the backported `csv` module. It is crucial to use `io.open` with `newline=''` and specify the `encoding` (e.g., 'utf-8') to handle text files correctly, mirroring Python 3's behavior.

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)

view raw JSON →