How to find a file in Python

Finding a file with a given filename in Python consists of searching through all files in the operating system and finding those which match the given filename.

Solution for How to find a file in Python : You can use os.walk() to walk through sub-directories to find matching files Call os.walk(“path/to/file”) with the desired starting path/to/file to return a generator of all filenames and sub-directories in path/to/file. Use a for loop to iterate over the generator and check each filename against name. Call os.path.join(root,name) to join each matching filename path to the parent directory path root and return the absolute path name of the filename as a string. If no matches are found, no output is printed.


how-to-find-a-file-in-python