Computer Science Mojo

~ David's Notes on coding, software and computer science




Post

How to check all files and find a file type in all directories in Python

Category: Python     Tag: Linux   Python  
By: David     On: Thu 06 August 2015      Pageviews: 5

Going through all the directories to find the path of a specific type of file is easy in Python. This helps with mass processing files.

Software

Reading

Find files

For this example, we have a folder called "messyFolder" which has all kinds of files and subdirectories inside. We are to locate the path of all ".tiff" and ".png" files.

import os, os.path
path = "messyFolder/"
for dirpath, dirnames, filenames in os.walk(path):
    for f in files:
        if f.endswith((".tiff", ".png")):
            print os.path.join(dirpath, f) 
            # the path starting at "messyFolder/"
            print os.path.abspath(os.path.join(dirpath, f)) 
            # the absolute path starting with "/home/" in Linux