Reputation: 959
I have a directory with a list of files and I would like to match the contents of the direcotry with a pattern
>>os.listdir(os.getcwd()) gives
[2010.1.1-19999, 2011.1.1-124444]
>> fnmatch.filter(os.listdir(os.getcwd()),"\d+\.\d\.\d\-\d+")
[]
The result is null and the fnmatch function does not pattern match the contents of the directory listing.
what is the error here ?
Upvotes: 0
Views: 534
Reputation: 1121196
"\d+\.\d\.\d\-\d+"
is not a fnmatch
globbing pattern, it's a regular expression. From the module documentation:
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 you wanted to use a regular expression, use the re
module to test your filenames:
import re
[filename for filename in os.listdir() if re.match(r"^\d+\.\d\.\d\-\d+$", filename)]
As a side note, if you find yourself using fnmatch.filter(os.listdir(directory), pattern)
, then just use glob.glob(os.path.join(directory, pattern))
instead.
Upvotes: 1