'Python3: csv circular import

This is my code:

import csv

with open('cars.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['ID'], row['CIP'], row['NAME'])

I'm getting this message:

$ python3 csv.py
Traceback (most recent call last):
  File "/home/jeusdi/projects/workarea/salut/load-testing/csv.py", line 1, in <module>
    import csv
  File "/home/jeusdi/projects/workarea/salut/load-testing/csv.py", line 4, in <module>
    reader = csv.DictReader(csvfile)
AttributeError: partially initialized module 'csv' has no attribute 'DictReader' (most likely due to a circular import)

Any ideas?



Solution 1:[1]

As pointed out by @buran in comments, you are overwriting the built-in csv model. Indeed, a python file is a module itself. More on this can be found here.

Just a little experiment to wrap your head around it. Try to modify your code in csv.py as follows:

import csv

print(csv) # tell me something about such a `csv`

now if you run such a file, you get something like this:

<module 'csv' from '/home/jeusdi/projects/workarea/salut/load-testing/csv.py'>
<module 'csv' from '/home/jeusdi/projects/workarea/salut/load-testing/csv.py'>

This happens because the print statement is run twice: the first time when you import csv, the second time when the module is executed by the interpreter. Note that your csv module is actually your file now (look at the path)! This is not want you want.

Then try to rename csv.py into my_csv.py, as suggested by @buran and run this renamed file. This time you get:

<module 'csv' from '/<built-in-module-path>/csv.py'>

Two things to note here:

  1. the print statement is run just once. This happens because this time import csv actually imports the built-in module that doesn't have any print statements. What you get in the standard output is the print(csv) in your my_csv.py.
  2. note that this time the path of csv points to the built-in Python module.

Solution 2:[2]

Try to rename your script csv.py

It cannot have the same name as the module

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Paulo