Change language

fnmatch — pattern matching Unix filename in Python

| |

This module is used for Unix shell style wildcard matching. fnmatch () compares one filename against a pattern and returns TRUE if they match, otherwise it returns FALSE. 
Comparison is case sensitive when the operating system uses a case sensitive file system. 
Special characters and their functions used in shell-style wildcards:

  • & # 39; * & # 39; — matches everything
  • & # 39;? & # 39; — matches any single character
  • & # 39; [seq] & # 39; — matches any character in seq
  • & # 39; [! seq] & # 39; — matches any character not in seq

Metacharacters must be enclosed in square brackets to literally match. For example, "[?]" Matches the character "?".

Functions provided by the fnmatch module

  1. fnmatch. fnmatch (filename, pattern) : This function checks if the given filename string matches the pattern string and returns a boolean value. If the operating system is case insensitive, both parameters will be normalized to all uppercase and lowercase before the comparison is performed.

    Example: script to search all files starting with & # 39; fnmatch & # 39 ; and ending with & # 39; .py & # 39;

    # Python program for illustration
    # fnmatch.fnmatch (file name, pattern)

    import fnmatch

    import os

     

    pattern = ’fnmatch _ *. py’

    print ’Pattern:’ , pattern

    print

     

    files = os.listdir ( ’. ’ )

    for   name in files:

    print ’Filename:% -25s% s’ % (name, fnmatch.fnmatch (name, pattern)

    Output:

     $ python fnmatch_fnmatch.py ​​Pattern: fnmatch _ *. py Filename: __init__.py False Filename: fnmatch_filter .py True Filename: fnmatch_fnmatch.py ​​True Filename: fnmatch_fnmatchcase.py True Filename: fnmatch_translate.py True Filename: index.rst False 
  2. fnmatch.fnmatchcase (filename, pattern) : this function performs case sensitive comparison and checks if the given filename string matches the template string and returns a boolean value.

    Example: script for case sensitive comparison, regardless of settings file system and opera system.

    # Python program for illustration
    # fnmatch.fnmatchcase (filename, template)

    import fnmatch

    import os

     

    pattern = ’FNMATCH _ *. PY’

    print ’Pattern:’ , pattern

    print

     

    files = os.listdir ( ’.’ )

      

    for name in files:

    print ’ Filename:% -25s% s’ % (name, fnmatch.fnmatchcase (name, pattern))

    Output:

     $ python fnmatch_fnmatchcase.py Pattern: FNMATCH _ *. PY Filename: __init__.py False Filename: fnmatch_filter.py False Filename: FNMATCH_FNMATCH.PY True Filename: fnmatch_fnmatchcase.py False_name Filerse.fnatem / pre> 
  3. fnmatch.filter (names, pattern): this function returns a subset of the list of names passed to the function that match the given pattern.

    Example. Filter files by multiple extensions.

    # Python program for illustration
    # fnmatch.filter (names, pattern)

    import fnmatch

    import os

     

    pattern = ’ fnmatch_ * .py’

    print ’Pattern:’ , pattern

      

    files = os.listdir ( ’.’ )

    print ’Files :’ , files

      

    print ’Matches:’ , fnmatch. filter (files, pattern)

    Output:

     $ python fnmatch_filter.py Pattern: fnmatch _ *. py Files: [ ’__init __. py’,’ fnmatch_filter.py’, ’fnmatch_fnmatch.py’,’ fnmatch_fnmatchcase.py’, ’fnmatch_translate.py’,’ index.rstatch’] Matches: [’fnmatch_filter.py_fnmatch , ’fnmatch_fnmatchcase.py’,’ fnmatch_translate.py’] 
  4. fnmatch.translate (pattern): this function returns a shell-style pattern converted to a regular expression for use with re.match () (re.match () will only match at the beginning of a line, not at the beginning of every line).

    # Programs and Python for illustration
    # fnmatch.translate (pattern)

    import fnmatch, re

     

    regex = fnmatch.translate ( ’* .txt’ )

    reobj = re. compile (regex)

     

    print (regex)

    print (reobj.match ( ’foobar.txt’ ))

    Output:

     ’(? S:. * . Txt)  Z’ _sre.SRE_Match object; span = (0, 10), match = ’foobar.txt’ 

This article is courtesy of Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically