fnmatch Module in Python

fnmatch Module in Python

>>> dir(fnmatch)
[‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing
__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘_compile_pattern’, ‘filter’, ‘fnm
atch’, ‘fnmatchcase’, ‘functools’, ‘os’, ‘posixpath’, ‘re’, ‘translate’]
>>>

We can see that this module contains other modules: re and os. Thanks to the fnmatch module, we can filter folders and files with shell patterns.

fnmatch(name, pattern) -> True if the name is matching the pattern

>>> fnmatch.fnmatch(“Kasia”, “K*s*a”)
True
>>> fnmatch.fnmatch(“Ala”, “?l?”)
True
>>> fnmatch.fnmatch(“Ala”, “?le”)
False
>>>

>>> for c in os.listdir(“D:/”):
…     fnmatch.fnmatch(c,”*.txt”)

False
True
False
True
True
False
False
False
False
False
False
False
False
False
False
True
False
False
False
>>>

It’s not exactly what we need. We should do something else:

>>> for c in os.listdir(“D:/”):
…     if fnmatch.fnmatch(c, “*.txt”):
…             print(c)

artyk.txt
derek.txt
dereka.txt
pliczek.txt
>>>

That’s it!

filter

>>> v = [“derek.txt”, “eta.csv”, “zeta.csv”, “pliczek.txt”]
>>> v
[‘derek.txt’, ‘eta.csv’, ‘zeta.csv’, ‘pliczek.txt’]

>>> fnmatch.filter(v, “*.csv”)
[‘eta.csv’, ‘zeta.csv’]
>>>

>>> fnmatch.filter(v, “*.txt”)
[‘derek.txt’, ‘pliczek.txt’]
>>>

We can use the filter function to filter a list against a pattern.

translate

>>> j = fnmatch.translate(“*.txt, c[eao]*.txt, t?.csv”)
>>> j
‘.*\\.txt\\,\\ c[eao].*\\.txt\\,\\ t.\\.csv\\Z(?ms)’
>>>

We can get the original regex (for reusing later).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s