Glob() का उपयोग करके Recursive File Search
Glob() का उपयोग करके Files को Recursively Find करने के लिए, आपको Python 3.5+ की आवश्यकता होती है। glob Module "**" Directive को Support करता है (जो केवल तभी Parse होता है जब आप Recursive Flag Pass करते हैं) जो Python को Directories में Recursively Look करने के लिए कहता है।
उदाहरण: Python 3.5+ में Glob का उपयोग
import glob
for filename in glob.iglob('src/**/*', recursive=True):
print(filename)
आप if Statement का उपयोग करके Filename को किसी भी Condition से Check कर सकते हैं।
Older Python Versions के लिए: os.walk का उपयोग
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)
यह आपके द्वारा Specify किए गए Regex से File Name को Match करेगा और उनके Names Print करेगा।
आधुनिक Approach: Pathlib (Python 3.4+)
from pathlib import Path
# सभी Files Recursively
for file in Path('src').rglob('*'):
print(file)
# Pattern Matching के साथ
for file in Path('src').rglob('*.py'):
print(file)
# Complex Pattern के लिए
import fnmatch
for file in Path('src').rglob('*'):
if fnmatch.fnmatch(file.name, 'test_*.py'):
print(file)
Performance Note:
glob.iglob()- Iterator Return करता है (Memory Efficient)glob.glob()- List Return करता है (सभी Results Memory में Load करता है)Path.rglob()- Iterator Return करता है, अधिक Object-Oriented