How to solve the Nameerror name path is not defined error?

Fix the nameerror path is not defined

Make sure to import the Path library into your Python script before you invoke any of the library methods as shown below:

from pathlib import Path
file_path = Path(r"C:\my_file.csv")

Understanding the name error message

Assume that you run the following line of code in your Python environment of choice such as: Jupyter, PyCharm or VsCode.

file_path = Path(r"C:\my_file.txt")

This will return the following NameError exception. Below is the screenshot from Jupyter, but you will get a similar error message in Python.

  1. The more widespread reason is that you simply didn’t import the Path library before using it in your code.
  2. The second option is that you might be using Python 2.x or a 3.X version that is earlier than 3.4. As the pathlib module was introduced in Python version 3.4, the Path library is not available for you to import into your script. If you need to use the Path library, consider upgrading your Python version to a later version . If that is not feasible, you might want to look into using the os library instead.

Fixing the Path not defined error

The fix is simple – and relevant to other name errors you might get. Always import the library you need to use (in this case Path), before using it in your code. As shown in the snippet below:

from pathlib import Path
#your code here
file_path = Path(r"C:\my_file.txt")

Suggested Learning

How to create a text or csv file with Python3?