0

Find file Using Python

This script will search the file and display the filename with path, and it will work on windows, Linux and MacOS

import os
import string
import platform
file_name  = input("Please enter the file name to search: ")
if platform.system() == "Windows":
    drives = string.ascii_uppercase
    valid_drives = []
    for each_drive in drives:
        if os.path.join(each_drive+":\\"):
            valid_drives.append(each_drive)
    for each_drive in valid_drives:
        for r,d,f in os.walk(each_drive):
            for each_f in f:
                if each_f == file_name:
                    print(os.path.join(r,each_f))
else:
    for r,d,f in os.walk("/"):
        for each_f in f:
            if each_f==file_name:
                print(os.path.join(r,each_f))

Sample output will be

/usr/local/bin/python3.7 /Users/jjames/Desktop/study/experiments/python/file_search.py
Please enter the file name to search: getpass.py
/usr/local/Cellar/python@2/2.7.17_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/getpass.py
/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/getpass.py
/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/getpass.py
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/getpass.py
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/getpass.py

Leave a Reply