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

วิธีใช้ Glob() หาไฟล์แบบ Recursive ใน Python

เพื่อใช้ glob() หาไฟล์แบบ Recursive คุณต้องใช้ Python 3.5+ โมดูล glob รองรับ Directive "**" (ซึ่ง Parse ได้ก็ต่อเมื่อส่ง Recursive Flag) ซึ่งบอก Python ให้ค้นหาใน Directories แบบ Recursive

ตัวอย่าง

import glob

for filename in glob.iglob('src/**/*', recursive=True):
    print(filename)

คุณสามารถตรวจสอบ Filename ด้วยเงื่อนไขที่ต้องการด้วย If Statement สำหรับ Python เวอร์ชันเก่า ใช้ os.walk เพื่อ Walk Directory แบบ Recursive และค้นหาไฟล์

ตัวอย่าง

import os, re, os.path

pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        print(file)

นี่จะ Match Filename กับ Regex ที่คุณระบุและพิมพ์ชื่อของพวกมัน