Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách quét đệ quy thư mục trong Python?


Bạn dùng hàm os.walk để duyệt cây thư mục trong Python.

Ví dụ

import os
for dirpath, dirs, files in os.walk("./my_directory/"):
    for filename in files:
        fname = os.path.join(dirpath, filename)
        with open(fname) as myfile:
            print(myfile.read())

Chương trình trên duyệt đệ quy cây my_directory và in nội dung từng file ra console.