Motivation
Sometimes you need to find files across multiple directories and / or directory hierarchies according to certain pattern.
E.g. find all image files with the jpg extension
You can use it to find files in a directory by using wildcard semantics.
Let’s say we have a directory structure like this:
glob_test/
|-- dir_a/
|-- text_01.txt
|-- text_02.txt
|-- text_03.txt
|-- dir_b/
|-- text_01.txt
|-- text_02.txt
|-- text_03.txt
|-- test_glob.py
Find files in directory
Let us find all text files in dir_a:
import glob
def test_glob_files():
text_files = glob.glob("./dir_a/text_*.txt")
print(text_files)
assert len(text_files) != 0
Find a file across multiple directories
Let’s find all occurences of text_01.txt in all directories
def test_glob_dirs():
text_files = glob.glob("./dir_*/text_01.txt")
print(text_files)
assert len(text_files) != 0