पायथन में किसी डायरेक्टरी के अंदर फ़ाइल खोजने के लिए, os.walk का उपयोग करके डायरेक्टरी ट्री को पार करें और फ़ाइल का मिलान करें।
उदाहरण
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')
जब आप इस स्क्रिप्ट को चलाते हैं और फ़ोल्डर स्ट्रक्चर ऐसा हो:
my_folder/
another_folder/
my_file
another_file
hello.py
my_file
आउटपुट
['/my_folder/another_folder/my_file', '/my_folder/my_file']