How to work with regex in Pathlib correctly?

Question:

I want find all images and trying to use pathlib, but my reg expression don’t work. where I went wrong?

from pathlib import Path
FILE_PATHS=list(Path('./photos/test').rglob('*.(jpe?g|png)'))
print(len(FILE_PATHS))
FILE_PATHS=list(Path('./photos/test').rglob('*.jpg'))#11104
print(len(FILE_PATHS))

0
11104
Asked By: Piter

||

Answers:

Get list of files using Regex

import re
p = Path('C:/Users/user/Pictures')
files = []
for x in p.iterdir(): 
    a = re.search('.*(jpe?g|png)',str(x))
    if a is not None:
        files.append(a.group())
Answered By: micah

Get list of files using pathlib.Path then filter list with regex using re

import re
from pathlib import Path
basepath = Path('C:/Users/user/Pictures')
pattern = '.*(jpe?g|png)'
matching_files = []

for _path in [p for p in basepath.rglob('*.*')]:
    if re.match(pattern, _path.name):
        matching_files.append(_path)
Answered By: wonderkid2
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.