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:

[email protected]:~ $cd ~/proj/python
[email protected]:~/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:

[email protected]:~/proj/python $ chmod a+rx
[email protected]:~/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:

[email protected]:~/proj/python $ mv
[email protected]:~/proj/python $ ./

Hope this saves you time some day, enjoy!

See Also

Keep Learning

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative I'm also a fan of SetApp for macOS: SetApp for macOS
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 Articles
17 Nov 2022

Video: awk delimiters

25 Oct 2022

macOS Ventura 13.0

21 Oct 2022

Video: How To Generate ed25519 key

Recent Tweets