Python program to find the path of a given file
By Lenin Mishra
If the file is in the current directory
Code
import os
filename = "findme.py"
print(os.path.abspath(filename))
Output
C:\Users\91824\PycharmProjects\pythonProject\findme.py
If the file is present in some other directory
Let’s say the file is present in some other directory. To get the path of the file, you have to use os.walk()
function to get it’s location..
Code
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)))
Output
C:\Users\91824\PycharmProjects\findme.py
C:\Users\91824\PycharmProjects\findme.py