How to find a file by name in Python
Published on Aug. 22, 2023, 12:16 p.m.
To find a file by name in Python, you can use the os.walk()
function which generates the file names in a directory tree, and then filter the results based on the filename. Here is an example code snippet to find a file named “example.txt” in a directory and its subdirectories:
import os
def find_file(filename, search_path):
for root, dir, files in os.walk(search_path):
if filename in files:
return os.path.join(root, filename)
Then you can call the find_file()
function and pass in the filename and the directory path to search in:
filename = 'example.txt'
search_path = '/Users/username/Documents'
file_path = find_file(filename, search_path)
print(file_path)
This will return the path of the first occurrence of the file with the given filename in the directory and its subdirectories. If the file is not found, the function will return None
.
Note that the search may take a while if you are searching in a large directory tree.