This error occurs when you try to use the csv
module without importing it first. You can solve this error by importing the module using the import
keyword. For example,
import csv filename = 'fiel.csv' with open(filename, 'r') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: print(row)
This tutorial will go through how to solve the error with code examples.
Table of contents
NameError: name ‘csv’ is not defined
Python raises the NameError when it cannot recognise a name in our program. In other words, the name we are trying to use is not defined in the local or global scope. A name can be related to a built-in function, module, or something we define in our programs, like a variable or a function.
The error typically arises when:
- We misspell a name
- We do not define a variable or function
- We do not import a module
In this tutorial, the source of the error NameError: name ‘csv
‘ is not defined is usually due to not importing the module. Let’s look at an example.
Example
The Python csv
module implements classes to read and write tabular data in Comma Separated Values (CSV) format. We can use the csv
module’s reader and writer objects to read and write sequences respectively. Let’s look at an example of writing some data to a csv file using the writer()
method:
rows = [['name', 'mass', 'charge', 'spin'], ['electron', '0.511', '-1', '1/2'], ['muon', '105.7', '-1', '1/2'], ['proton','938.3', '+1', '1/2'], ['Z-boson','80433', '0', '0']] filename = 'particles_info.csv' with open(filename, 'w') as csvf: csvwriter = csv.writer(csvf) csvwriter.writerows(rows)
In the above code, we define a nested list, where each list is a row of strings. The first list are the fields we want to appear in the csv file and the remaining lists are the rows containing the information for each field.
Then we use a context manager to open a file in write mode, create a writer object using csv.writer()
and then csv.writerows()
to write the multiple rows.
Let’s run the code to see what happens:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [1], in <cell line: 9>() 7 filename = 'particles_info.csv' 9 with open(filename, 'w') as csvf: ---> 11 csvwriter = csv.writer(csvf) 12 csvwriter.writerows(rows) NameError: name 'csv' is not defined
The error occurred because we did not import the csv
module. Although csv
is a built-in module we still need to import it.
Solution #1: Use import keyword
We can import the module by putting an import statement at the top of the program. Let’s look at the update code:
import csv rows = [['name', 'mass', 'charge', 'spin'], ['electron', '0.511', '-1', '1/2'], ['muon', '105.7', '-1', '1/2'], ['proton','938.3', '+1', '1/2'], ['Z-boson','80433', '0', '0']] filename = 'particles_info.csv' with open(filename, 'w') as csvf: csvwriter = csv.writer(csvf) csvwriter.writerows(rows)
When we run this code, we will successfully create a file in our working directory called particles_info.csv
containing the particle information.
Solution #2: Use from keyword
We can also use the from
keyword to import a specific variable, class or function from a module. In this case, we want to import the writer
class from the csv
module.
Using the from
keyword means we do not have to specify the csv
module in the rest of the program, we only need the writer
class.
Let’s look at the updated code:
from csv import writer rows = [['name', 'mass', 'charge', 'spin'], ['electron', '0.511', '-1', '1/2'], ['muon', '105.7', '-1', '1/2'], ['proton','938.3', '+1', '1/2'], ['Z-boson','80433', '0', '0']] filename = 'particles_info.csv' with open(filename, 'w') as csvf: csvwriter = writer(csvf) csvwriter.writerows(rows)
When we run this code, we will successfully create a file in our working directory called particles_info.csv
containing the particle information.
The from
keyword is also useful for importing multiple classes, functions or variables from a module. Let’s look at an example of importing the writer
and reader
classes from the csv
module.
from csv import writer, reader rows = [['name', 'mass', 'charge', 'spin'], ['electron', '0.511', '-1', '1/2'], ['muon', '105.7', '-1', '1/2'], ['proton','938.3', '+1', '1/2'], ['Z-boson','80433', '0', '0']] filename = 'particles_info.csv' with open(filename, 'w') as csvf: csvwriter = writer(csvf) csvwriter.writerows(rows) with open(filename, 'r') as csvf: csvreader = reader(csvf) fields = next(csvreader) for row in csvreader: print(row)
In the above code, we use the writer()
class to create a writer object and write the data to a csv
file. Then, we use the reader()
class to create a reader object to read the data from the file and print each row as a list of strings.
Let’s run the code to get the result:
['electron', '0.511', '-1', '1/2'] ['muon', '105.7', '-1', '1/2'] ['proton', '938.3', '+1', '1/2'] ['Z-boson', '80433', '0', '0']
Summary
Congratulations on reading to the end of this tutorial!
For further reading on NameErrors, go to the articles:
- How to Solve Python NameError: name ‘os’ is not defined
- How to Solve Python NameError: name ‘time’ is not defined
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.