Hope you are all doing well.
I am currently using fnmatch to match for file names against patterns.
I have not had any issues with simple patterns involving *,?,[seq]
as mentioned in the fnmatch documentation.
However I am not able to figure out a way to include other options such as +([0-9]).txt
or [0-9]{6}.txt
I will maybe explain what I am trying to achieve. Assume we have 4 files in our source path.
123456.txt (No. of digits will vary)
123_test.txt
test_123.txt
123_test_456.txt
What pattern should be given in fnmatch that matches the file 123456.txt alone while ignoring the other patterns.
import fnmatch
from pathlib import Path
source_file_path = "/files/tst_files/"
source_file_pattern = "*.txt" # 4 Matches - All 4 four files
# source_file_pattern = "*[0-9].txt" # 3 Matches - 123_test_456.txt, 123456.txt, test_123.txt
# source_file_pattern = "[0-9]*.txt" # No Matches
# source_file_pattern = "\b\d+\.txt\b" # No Matches
files = Path(source_file_path).glob('*')
for file in files:
if fnmatch.fnmatch(file, source_file_pattern):
print(file)
Env : Python 3.8
Thanks for all the help in advance.