Find path to the given file using Python
Last Updated :
02 Aug, 2024
We can get the location (path) of the running script file .py with __file__. __file__ is useful for reading other files and it gives the current location of the running file. It differs in versions. In Python 3.8 and earlier, __file__ returns the path specified when executing the Python command.
We can get a relative path if a relative path is specified. If we specify an absolute path, an absolute path is returned. But in Python 3.9 and later, __file__ always returns an absolute path, the OS module provides various utilities.
Ways to Get the Current Directory in Python with OS
There are many ways to get the current directory in Python with OS. Here, we are using some generally used ways to get the current directory in Python with OS those are following.
Find the path to the given file using Path.cwd()
Here, the idea of the Current Working Directory (CWD) holds an important place. Think of the CWD as the folder that the Python is running in. Python assumes that the file starts in the CWD if it is called simply by name, so a name-only reference will only work if the file is in Python's CWD. The Path.cwd() returns the current directory.
Python
from pathlib import Path
print(Path.cwd())
Output:
C:\Users\int.suraj.gupta
Get the Current Directory in Python with OS using os.getcwd()
We can get the absolute path of the current working directory. So depending upon the version used, either a relative path or absolute path is retrieved. In order to obtain the Current Working Directory in Python, use the os.getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
Python
import os
print('Get current working directory : ', os.getcwd())
Output:
Get current working directory : C:\Users\int.suraj.gupta
Get the Current Directory in Python with OS using pathlib.Path().absolute()
This function of the Python OS module returns the string containing the absolute path to the current working directory.
Python
import pathlib
# current working directory
print(pathlib.Path().absolute())
Output:
C:\Users\int.suraj.gupta
Find the Path to the Given File using os.path.basename
We can get the file name and the directory name of the running file in the below way. The key thing to understand about __file__ is that the interpreter adjusts it at runtime so that Python knows which file it is dealing with when the script uses several modules. The benefit of calling Path( file__) is that it returns a string containing the path and the file you are currently working on.
- You can call __file__ while modifying a file. As a result, if you attempt to call it from the shell interpreter, it will not execute.
- __file__ does not function in a Jupyter notebook's context.
Python
import os
print('File name : ', os.path.basename(__file__))
print('Directory Name: ', os.path.dirname(__file__))
Output:
Find the Path to the Given File using os.path.abspath
It may sound complicated, but os.path.abspath() simply means that this method returns the pathname to the path supplied as an argument to this function. The documentation claims that this method produces a normalized absolutized version of the pathname path.
Example 1: To get the absolute path of the running file.
Python
import os
print('Absolute path of file: ',
os.path.abspath(__file__))
print('Absolute directoryname: ',
os.path.dirname(os.path.abspath(__file__)))
Output:

Example 2: If we specify an absolute path in os.path.abspath(), it will be returned as it is, so if __file__ is an absolute path, no error will occur even if we set os.path.abspath(__file__)
Python
import os
pythonfile = 'pathfinding.py'
# if the file is present in current directory,
# then no need to specify the whole location
print("Path of the file..", os.path.abspath(pythonfile))
for root, dirs, files in os.walk(r'E:\geeksforgeeks\path_of_given_file'):
for name in files:
# As we need to get the provided python file,
# comparing here like this
if name == pythonfile:
print(os.path.abspath(os.path.join(root, name)))
Output:
Similar Reads
Handling TOML files using Python
In this article, we will see how we can manipulate TOML files using tomli/tomlib module in Python. What is a TOML file? TOML stands for Tom's Obvious, Minimal Language, here Tom refers to the creator of this language Tom-Preston Werner. It is a file format, especially for files that hold some kind o
5 min read
Read Html File In Python Using Pandas
In Python, Pandas is a powerful library commonly used for data manipulation and analysis. While it's primarily used for working with structured data such as CSV files, Excel spreadsheets, and databases, it's also capable of reading HTML files and extracting tabular data from them. In this article, w
5 min read
Setting file offsets in Python
Prerequisite: seek(), tell() Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer
4 min read
Create Inverted Index for File using Python
An inverted index is an index data structure storing a mapping from content, such as words or numbers, to its locations in a document or a set of documents. In simple words, it is a hashmap like data structure that directs you from a word to a document or a web page. Creating Inverted Index We will
3 min read
Using the Cat Command in Python
The cat command is a Linux shell command. It is the shorthand for concatenate. It is placed among the most often used shell commands. It could be used for various purposes such as displaying the content of a file on the terminal, copying the contents of a given file to another given file, and both a
4 min read
Writing to file in Python
Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail.Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following th
4 min read
Find the text of the given tag using BeautifulSoup
Web scraping is a process of using software bots called web scrapers in extracting information from HTML or XML content of a web page. Beautiful Soup is a library used for scraping data through python. Beautiful Soup works along with a parser to provide iteration, searching, and modifying the conten
2 min read
Convert Text File to CSV using Python Pandas
Converting Text File to CSV using Python Pandas refers to the process of transforming a plain text file (often with data separated by spaces, tabs, or other delimiters) into a structured CSV (Comma Separated Values) file using the Python Pandas library.In this article we will walk you through multip
2 min read
Interact with files in Python
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complica
6 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read