close

How do i search directories and find files that match regex?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do i search directories and find files that match regex in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do i search directories and find files that match regex?

  1. How do i search directories and find files that match regex?

    Here's an alternative using glob.
    from pathlib import Path rootdir = "/mnt/externa/Torrents/completed" for extension in 'zip rar r01'.split():

  2. search directories and find files that match regex

    Here's an alternative using glob.
    from pathlib import Path rootdir = "/mnt/externa/Torrents/completed" for extension in 'zip rar r01'.split():

Method 1

import os
import re

rootdir = "/mnt/externa/Torrents/completed"
regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.match(file):
       print(file)

CODE BELLOW ANSWERS QUESTION IN FOLLOWING COMMENT

That worked really well, is there a way to do this if match is found on regex group 1 and do this if match is found on regex group 2 etc ? – nillenilsson

import os
import re

regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')
rx = '(.*zip$)|(.*rar$)|(.*r01$)'

for root, dirs, files in os.walk("../Documents"):
  for file in files:
    res = re.match(rx, file)
    if res:
      if res.group(1):
        print("ZIP",file)
      if res.group(2):
        print("RAR",file)
      if res.group(3):
        print("R01",file)

It might be possible to do this in a nicer way, but this works.

Method 2

Here’s an alternative using glob.

from pathlib import Path

rootdir = "/mnt/externa/Torrents/completed"
for extension in 'zip rar r01'.split():
    for path in Path(rootdir).glob('*.' + extension):
        print("match: " + path)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read