How to loop over specific files in python.

Hi all,

Generally we wish to loop over specific category of files in python. So how do we do this.

Method 1 : -

Using glob
import glob, os
for file in glob.glob("*.txt"):
Method 2 :-

Without glob
import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
Method 3 :-

Using Os.walk
import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

Original source : -