Filename pattern matching in Python with pathlib.Path.glob()


Python tip:

You can use pathlib.Path.glob() to list all files matching a given pattern.

For example, you can list names of all txt files located inside the same directory as your Python script👇

import pathlib

parent_folder = pathlib.Path(__file__).parent.absolute()

print(parent_folder)
for file in parent_folder.glob("*.txt"):
    print(file.name)

"""
example.txt
first.txt
second.txt
"""