Computer Science Atlas
Snippets

Python 3: Path of the Current Script File and Directory

February 18, 2021|Updated February 23, 2021
 
Table of Contents

Using pathlib (Python 3.4 and Up)

File Path

To get the file path of the current Python script:

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:

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:

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:

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:

print( __file__ )
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