How to find a file using Python?

PythonServer Side ProgrammingProgramming

To find a file within a directory using python, you can walk the directory tree using os.walk and find the file as follows −

Example

import os
def find_file(file_name, directory_name):
    files_found = []
    for path, subdirs, files in os.walk(directory_name):
        for name in files:
            if(file_name == name):
                file_path = os.path.join(path,name)
                files_found.append(file_path)
    return files_found
find_file('my_file.txt', 'my_folder')

When you run this script and have folder structure like −

my_folder/
    another_folder/
        my_file
        another_file
    hello.py
    my_file

Output

You'll get the output −

['/my_folder/another_folder/my_file', '/my_folder/my_file']
raja
Published on 27-Dec-2017 11:53:44
Advertisements