Thursday, December 10, 2015

CSV Reading Error (Python)

Just encountered a very ambiguous error in Python while reading a .csv file using the csv library in Python.

The solution made me feel pretty dumb. That is why I am blogging this to remember. From: https://docs.python.org/2/library/csv.html This is the code snippet I was trying to execute to read csv file at path /home/superuser/Desktop/day.csv.
import csv
with open('./day.csv', 'rb') as csvfile:
  r = csv.reader(csvfile, delimiter=' ', quotechar='|')
  for row in r:
    print ', '.join(row)
Python shell was showing error,
AttributeError: 'module' object has no attribute 'read'
Which made me thing that I'm importing wrong csv library. May be this import csv isn't importing the correct CSV I need. I was correct.
But the solution was pretty awkward. I was saving my file as "csv.py" and my program "csv.py" itself was importing itself.
Renaming the script to some other name resolved this issue.
Thanks to bernie's answer here:
http://stackoverflow.com/questions/9711799/csv-module-attributeerror

No comments :

Post a Comment