What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python

That is a clever way to refer to paths regardless of the script location. The cryptic line you're referring is:

os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))

There are 3 methods and a 2 constants present:

  1. abspath returns absolute path of a path
  2. join join to path strings
  3. dirname returns the directory of a file
  4. __file__ refers to the script's file name
  5. pardir returns the representation of a parent directory in the OS (usually ..)

Thus, the expression returns the full path name of the executing script in a multiplatform-safe way. No need to hardwire any directions, that's why it is so useful.

There might be other approaches to get a parent directory of where a file is located, for example, programs have the concept of current working directory, os.getcwd(). So doing os.getcwd()+'/..' might work. But this is very dangerous, because working directories can be changed.

Also, if the file is intended to be imported, the working directory will point to the importing file, not the importee, but __file__ always points to the actual module's file so it is safer.

Hope this helps!

Edit: P.S. - Python 3 greatly simplifies this situation by letting us treat paths in an object-oriented manner, so the above line becomes:

from pathlib import Path
Path(__file__).resolve().parent.parent

__file__ represents the file the code is executing from

os.path.dirname(__file__) gives you the directory the file is in

os.path.pardir stands for ".." which means one directory above the current one

os.path.join(os.path.dirname(__file__), os.path.pardir) joins the directory name and ".."

os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) resolves the above path and gives you an absolute path for the parent directory of the directory your file is in