Computer Science Atlas
Code Review

Python 3 Examples: Path of the Current Script File and Directory

February 18, 2021|Last Updated February 23, 2021
 

Using pathlib (Python 3.4 and Up)

File Path

To get the file path of the current Python script:

Copy
from pathlib import Path

script_path = Path( __file__ ).absolute()

print( script_path )
1
2
3
4
5
from pathlib import Path

script_path = Path( __file__ ).absolute()

print( script_path )

Directory

If you want the path of the directory that the current Python script file is in:

Copy
from pathlib import Path

script_dir = Path( __file__ ).parent.absolute()

print( script_dir )
1
2
3
4
5
from pathlib import Path

script_dir = Path( __file__ ).parent.absolute()

print( script_dir )

Using os.path

File Path

To get the file path of the current Python script:

Copy
import os

script_path = os.path.abspath( __file__ )

print( script_path )
1
2
3
4
5
import os

script_path = os.path.abspath( __file__ )

print( script_path )

Directory

If you want the path of the directory that the current Python script file is in:

Copy
import os

script_dir = os.path.abspath( os.path.dirname( __file__ ) )

print( script_dir )
1
2
3
4
5
import os

script_dir = os.path.abspath( os.path.dirname( __file__ ) )

print( script_dir )

__file__

__file__ is an attribute (special variable) set by Python in modules that are loaded from files (usually, but not required to be, files that have the .py extension). The attribute is not set when you're running code inside a Python shell (the python or python3 command line program), in a Jupyter notebook, or in other cases where the module is not loaded from a file.

Although we could use __file__ by itself:

Copy
print( __file__ )
1
print( __file__ )

it is not guaranteed to be an absolute path (i.e., it may be a relative path). The pathlib.Path.absolute() or os.path.abspath call ensures that it is an absolute path.

References and Notes