[PYTHON] Generate all files with a specific extension

It licks all files under the specified directory and returns only the file path of the file with the desired extension as a generator. You can do this by using ʻos.walk`.

I think it's a frequently used operation, but I immediately forget how to write it, so I'll make it a function for the future as a memo. It can be used with both Python 2 and 3.

import os


def walk_files_with(extension, directory='.'):
    """Generate paths of all files that has specific extension in a directory. 

    Arguments:
    extension -- [str] File extension without dot to find out
    directory -- [str] Path to target directory

    Return:
    filepath -- [str] Path to file found
    """
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            if filename.lower().endswith('.' + extension):
                yield os.path.join(root, filename)

Actually, it is used like this.

for filepath in walk_files_with('csv', './data/'):
    print(filepath)

If you have Python 3.4 or above, it may be smarter to use pathlib.

Recommended Posts

Generate all files with a specific extension
Enumerate files with a specific extension
Generate a normal distribution with SciPy
Generate a Pre-Signed URL with golang
[Python] Generate a password with Slackbot
Search for files with the specified extension
Use shutil to delete all folders with a small number of files
Create a command to delete all temporary files generated in a specific folder
[Python] Get the files in a folder with Python
Erase & generate serial number files with shell script
Recursively search all files with multiple specified extensions
Clone with a specific branch / tag in GitPython
Sort dict in dict (dictionary in dictionary) with a specific key
Configure a module with multiple files in Django
[Python] Rename all image files in a specific folder by shooting date and time
Extract elements other than a specific index with Numpy
Generate a random sentence from your tweet with trigram
I tried to automatically generate a password with Python3
2 ways to read all csv files in a folder
Apply conda's env to a specific directory with pyenv-vertualenv
Stop an instance with a specific tag in Boto3
Upload files with Django
A4 size with python-pptx
Give the history command a date and time and collect the history files of all users with a script
Decorate with a decorator
Create a list in Python with all followers on twitter
Generate a password that is easy to remember with apg
Installation procedure for Python and Ansible with a specific version
Detect objects of a specific color and size with Python
Process the files in the folder in order with a shell script
How to extract other than a specific index with Numpy
Delete all libraries installed on pip with a single command