How to Get Path of the Current File in Python

Manav Narula Feb 02, 2024
  1. Use of the pathlib Module to Get the Path of Files and Current Working Directory
  2. Use the os Module to Get the Path of Files and the Current Working Directory
How to Get Path of the Current File in Python

In Python, we can work with many files and modules and constantly interact with the file system. To import or export files, we need to know the correct path and directory of such files; otherwise, errors are raised. It is also essential to know the path of the currently running Python script or the path of some other file.

The current working directory is the directory of Python in which we are currently working on.

This tutorial will introduce how to get the full path and directories of the current file and the current working directory in Python.

Use of the pathlib Module to Get the Path of Files and Current Working Directory

The pathlib library is available to Python 3.x and up and contains classes, methods to handle file-path-related problems.

In the code below, we will extract the path of a Python script using the functions provided by the pathlib module:

import pathlib

print(pathlib.Path(__file__).parent.absolute())

Output:

C:\Sample\Python

The absolute() method returns the full path of the file, and the parent() function retrieves the directory of the file from this path.

To get the current working directory, we remove the file name from the above function. The following code shows how:

import pathlib

print(pathlib.Path().absolute())

Output:

C:\Sample\Python

Use the os Module to Get the Path of Files and the Current Working Directory

The os library is used to interact with the Operating System and has functions available to retrieve full paths of the files. This method works with Python 2.x as well.

The abspath() function can get the required file’s path, and the dirname() function gets the directory from the full path.

For example:

import os

print(os.path.dirname(os.path.abspath(__file__)))

Output:

C:\Sample\Python

We cannot use the dirname() function directly to get a file’s directory as it returns an empty string.

We can also use the realpath() function as an alternative to the abspath() function. It removes any symbolic links if present from the path.

import os

print(os.path.dirname(os.path.realpath(__file__)))

Output:

C:\Sample\Python

To get the current working directory, we can use the getcwd() method that returns the current directory path. We can pass this path to the dirname() method to get the directory.

For example:

import os

print(os.path.abspath(os.getcwd()))

Output:

C:\Sample\Python
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Path