Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสแกนไดเรกทอรีแบบ Recursive ใน Python

ใช้ฟังก์ชัน os.walk เพื่อเดินผ่านต้นไม้ไดเรกทอรีใน Python

ตัวอย่าง

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

โปรแกรมนี้จะเดินผ่าน my_directory แบบ recursive และพิมพ์เนื้อหาของทุกไฟล์ออกมาที่คอนโซล