python

How to get current file path in Python

Python is a powerful programming language that is widely used in many different industries today. One of its key features is its ability to manipulate file paths. This can be extremely useful when working with files in Python. In this article, we will show you how to get the current file path in Python.

import pathlib

path = pathlib.Path().resolve() # working directory path

file_path = pathlib.Path(__file__).parent.resolve() # path where script is running

print(str(path))

print(str(file_path))

The first line imports the pathlib module. The second line uses the Path() method to get the current working directory path. The third line uses the Path() method to get the path where the script is running. The fourth line prints the working directory path. The fifth line prints the path where the script is running.


Using pathlib module

We can use the pathib module to get the current project path or script file path in Python.

Get the working directory path

import pathlib
path = pathlib.Path().resolve()

print(str(path))

Output Example

/Users/uname/Desktop/Workspace/project_name

Get the current script file path

import pathlib
path = pathlib.Path(__file__).parent.resolve()

print(str(path))

Output example

 /Users/uname/Desktop/Workspace/project_name/app/filename.py

Was this helpful?