Skip to content

Potential broken approach of reading csv files #286

@warwickmm

Description

@warwickmm

The following pattern is used often to read csv files:

with open(filename, 'rU') as csvfile:
    reader = unicodecsv.DictReader(csvfile)

I think this worked in python2 since the str and bytes types were synonymous. However, this breaks in python3 since unicodecsv expects the file to be opened in binary mode, which it is not.

For example, the following fails in python3 with the error AttributeError: 'str' object has no attribute 'decode'

import unicodecsv

filename = 'openelex/us/md/mappings/md.csv'
with open(filename, "r") as data:
    reader = unicodecsv.DictReader(data)
    for row in reader:
        print(row)

Using csv instead of unicodecsv fixes the issue.

import csv

filename = 'openelex/us/md/mappings/md.csv'
with open(filename, "r") as data:
    reader = csv.DictReader(data)
    for row in reader:
        print(row)

Is there something wrong with my setup, or is this broken for other people as well?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions