Python program to find the path of a given file
Learn how to find the path of any file in Python.
Scenario 1 - If the file is in the current directory
If the file is in the current directory, you can use the
abspath() function to find the absolute path of the file.
import os filename = "findme.py" print(os.path.abspath(filename))
Scenario 2 - If the file is present in some other directory
If the file is in a different directory than your python file, you have to use
os.walk() function to get it's path.
import os filename = "findme.py" dir_to_search = "C:\\Users\\91824\\PycharmProjects\\" for root, dirs, files in os.walk(dir_to_search): # print(root, dirs, files) for name in files: if name == filename: # Path of the file print(os.path.join(root, name)) # Absolute Path of the file print(os.path.abspath(os.path.join(root, name)))