Seraphim
Seraphim

Reputation: 181

Using fnmatch to locate all folders with name pattern

I have a sequence of folders with the naming patter: %y-%m-%d And I want to use fnmatch to find them and append them to a list. I am currently using this code:

    for root, subs, files in os.walk('.'):
      for name in subs:
        if fnmatch.fnmatch(name, '%y-%m-%d'):
                folderlist.append(os.path.join(root, name))

But this results in an empty folderlist. I know the reason for this (%y-%m-%d is not a proper pattern as understood by fnmatch, but I dont know how to get around it.

Upvotes: 1

Views: 977

Answers (2)

Tupteq
Tupteq

Reputation: 3095

I think re would be better instead of fnmatch, but here it is:

import os
from fnmatch import fnmatch

folderlist = []
for root, subs, files in os.walk('.'):
    for name in subs:
        if fnmatch(name, '[12][0123456789][0123456789][0123456789]-[01][0123456789]-[0123][0123456789]'):
            folderlist.append(os.path.join(root, name))

print(folderlist)

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can use a regex:

reobj = re.compile('\d{4}-\d{2}-\d{2}')
for root, subs, files in os.walk('.'):
    for name in subs:
        if reobj.match(name):
            print(name)

Upvotes: 1

Related Questions