5

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Piter
  • 61
  • 1
  • 4
  • 4
    Seems like you are mixing regex and glob syntax, the `rglob` function expects a glob selector as an arugment, not regex – mousetail Jan 07 '22 at 21:12

2 Answers2

3

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())
micah
  • 838
  • 7
  • 21
1

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)
wonderkid2
  • 4,654
  • 1
  • 20
  • 20