Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để tìm một tệp bằng Python?


Để tìm tệp trong thư mục bằng python, bạn có thể đi bộ cây thư mục bằng os.walk và tìm tệp như sau -

Ví dụ

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')

Khi bạn chạy tập lệnh này và có cấu trúc thư mục như -

my_folder/
    another_folder/
        my_file
        another_file
    hello.py
    my_file

Đầu ra

Bạn sẽ nhận được đầu ra -

['/my_folder/another_folder/my_file', '/my_folder/my_file']