4

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)
Mohan
  • 145
  • 2
  • 8
  • 2
    I've closed this as dupe of https://stackoverflow.com/questions/4568580/python-glob-multiple-filetypes, but reopened. I think you should avoid glob in that case because it will scan directories more than once. Better compute the list of files and check patterns. – Jean-François Fabre Dec 15 '17 at 21:54
  • 3
    Use `os.walk()` and filter on a filename-by-filename basis. `glob.glob()` does not support multiple patterns. – zwer Dec 15 '17 at 21:57
  • use [pathlib](https://docs.python.org/3/library/pathlib.html): https://stackoverflow.com/a/57054058/9935654 – Carson Jun 16 '21 at 09:21

1 Answers1

5

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))
srikavineehari
  • 2,502
  • 1
  • 11
  • 21