JoshG
JoshG

Reputation: 6735

Pattern/regex formatting for Python fnmatch

All of my filenames contain the following pattern:

datasetname_%Y-%m-%d_%H.%M.%S.out

The timestamp is added using time.strftime("%Y-%m-%d_%H.%M.%S")

What I want to do is check to see if the filename already contains the timestamp, and if it does, strip it off. For that I can use split. And I can use fnmatch to test if the filename contains the pattern.

The part I'm having trouble with is figuring out the regex pattern to give fnmatch from the format I'm using.

Any help and/or suggestions would be greatly appreciated.

Upvotes: 1

Views: 6289

Answers (2)

JoshG
JoshG

Reputation: 6735

This ended up seeming to work for me:

regexp = re.compile('_([0-9-_.]+\...)')
if regexp.search(fileName) is not None:
    #Do something with the filename

I used the pattern based on drewk's comment above (thank you). So far the pattern seems to work, but it might need some tweaking. In any case, it got me a lot further than where I was.

Also thanks to WombatPM. Your answer actually helped with a separate problem I was having.

Upvotes: 1

WombatPM
WombatPM

Reputation: 2609

I think you may be making this more complicated than it needs to be.

from the python documentation http://docs.python.org/2/library/fnmatch.html

This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module).

If your datasetname is derf the example becomes:

    import fnmatch
    import os

    dsn = 'derf_'

    for file in os.listdir('.'):
        if fnmatch.fnmatch(file, dsn+'*.out'):
            print file

Upvotes: 2

Related Questions