Search code examples
pythondirectoryfilepathglobpython-os

Use multiple file extensions for glob to find files


I am using glob to list out all my python files in the home directory by this line of code. I want to find all .json files too along with py files, but I couldn't found any to scan for multiple file types in one line code.

for file in glob.glob('/home/mohan/**/*.py', recursive=True):
    print(file)

Solution

  • You could use os.walk, which looks in subdirectories as well.

    import os
    
    for root, dirs, files in os.walk("path/to/directory"):
        for file in files:
            if file.endswith((".py", ".json")): # The arg can be a tuple of suffixes to look for
                print(os.path.join(root, file))