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
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)
 
Method 2 :-

Without glob
import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(file)
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 : - https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python

Comments

Popular posts from this blog

SOX - Sound eXchange - How to use SOX for audio processing tasks in research.

How to get video or audio duration of a file using ffmpeg?

Sox of Silence - Original post - http://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/