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 csv.py

with the following contents:

!/usr/local/bin/python3

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 csv.py
greys@mcfly:~/proj/python $ ./csv.py
Traceback (most recent call last):
  File "./csv.py", line 3, in 
    import csv
  File "/Users/greys/Documents/proj/python/csv.py", 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 csv.py 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 csv.py csv-test.py
greys@mcfly:~/proj/python $ ./csv-test.py
username,userid,fullname,homedir,password_hash

Hope this saves you time some day, enjoy!

See Also




Contact Me

Follow me on Facebook, Twitter or Telegram:
Recommended
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