ในการค้นหาไฟล์ภายในไดเร็กทอรีโดยใช้ python คุณสามารถเดินไปตามแผนผังไดเร็กทอรีโดยใช้ 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']