AttributeError: module has no attribute in Python

Python Python

One very common mistake almost everyone makes in Python is this: you import a module for some additional functionality, but Python won’t interpret your code and instead will return you an AttributeError message.

AttributeError: module ‘csv’ has no attribute ‘reader’

I needed to parse a CSV file, so I created a new file for the Python code using vim editor:

greys@mcfly:~ $cd ~/proj/python
greys@mcfly:~/proj/python $ vim

with the following contents:


import csv

with open('input-data/sample.csv', newline='') as csvfile:
    sample_report = csv.reader(csvfile, delimiter=' ', quotechar='|')

    for row in sample_report:             
        print(', '.join(row))

When I attempted to run this code, I received an error:

greys@mcfly:~/proj/python $ chmod a+rx
greys@mcfly:~/proj/python $ ./
Traceback (most recent call last):
  File "./", line 3, in 
    import csv
  File "/Users/greys/Documents/proj/python/", line 6, in 
    face_report = csv.reader(csvfile, delimiter=' ', quotechar='|')
AttributeError: module 'csv' has no attribute 'reader'

csv is a standard module in the Python 3 library, so this puzzled me a bit. It definitely has the reader method, as examples on many websites show.

So Why This AttributeError Message?

Having double-checked for typos and indentation, I realised that this mistake is probably related to my filename.

You see, what’s happening is that my code tries to import Python module named csv. It’s a standard module, but purist approach insists on not making such assumptions. That’s why the Python interpreter checks current directory for any modules named csv before it goes searching further in its standard locations.

Because my own example code was saved in the file, I was making it import itself instead of the standard (global) Python 3 csv module.

Solution for this Type of AttributeError

The fix is simple: rename your file to something else and it will no longer be importing itself. Python will not find any modules with specified name in your current directory and will then assume you’re definitely talking about a module from standard library.

Have a look, once I renamed the file it started working:

greys@mcfly:~/proj/python $ mv
greys@mcfly:~/proj/python $ ./

Hope this saves you time some day, enjoy!

See Also

Contact Me

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!

Recent Tweets