Search for a file using a wildcard

Viewed 87985

I want get a list of filenames with a search pattern with a wildcard. Like:

getFilenames.py c:\PathToFolder\*
getFilenames.py c:\PathToFolder\FileType*.txt
getFilenames.py c:\PathToFolder\FileTypeA.txt

How can I do this?

5 Answers

If you're on Python 3.5+, you can use pathlib's glob() instead of the glob module alone.

Getting all files in a directory looks like this:

from pathlib import Path
for path in Path("/path/to/directory").glob("*"):
    print(path)

Or, to just get a list of all .txt files in a directory, you could do this:

from pathlib import Path
for path in Path("/path/to/directory").glob("*.txt"):
    print(path)

Finally, you can search recursively (i.e., to find all .txt files in your target directory and all subdirectories) using a wildcard directory:

from pathlib import Path
for path in Path("/path/to/directory").glob("**/*.txt"):
    print(path)
Related