Python Tutorial - fnmatch module

Python Exercise Lists

For Filename Matching in Python

The fnmatch module is mainly used for file name matching. Its ability is more powerful than simple string matching, but slightly weaker than using regular expressions. If you only need to use simple wildcards to complete file name matching in data processing operations, using the fnmatch module is a good choice.

The following table shows the commonly used functions and their functions in the fnmatch module.

Function Name Features
fnmatch.filter(names, pattern) Filters the names list and returns a subset of the filenames in the names list that match pattern.
fnmatch.fnmatch(filename, pattern) Determines whether filename matches the specified pattern string
fnmatch.fnmatchcase(filename, pattern) Has roughly the same functionality as the fnmatch() function, except that the function is case sensitive.
fnmatch.translate(pattern) Converts a UNIX shell-style pattern string to a regular expression.

The fnmatch module uses the UNIX shell style to match filenames. It supports the following wildcards:

• *: Can match any number of any characters.
• ? : Matches any arbitrary character.
• [Character Sequence]: Can match any character in the character sequence in brackets. This character sequence also supports midline line notation. For example, [a-c] can represent any of the a, b, and c characters.
• [! Character sequence]: matches any character that is not in the character sequence in the brackets.

For example, the following program demonstrates the usage and function of some functions in Table above:

import fnmatch
print(fnmatch.filter(['dlsf', 'ewro.txt', '', ''], '*.txt'))
for file in ['word.doc','','my_file.txt']:
    if fnmatch.fnmatch(a,'*.txt'):
print([addr for addr in ['word.doc','','a.txt','a.TXT'] if fnmatch.fnmatchcase(addr, '*.txt')])

The output is:


Python Tempfile Module

Generate temporary files and temporary directories. The tempfile module is designed to create temporary files and temporary directories. It works well on both UNIX platforms and Windows platforms.

Functions commonly used in the tempfile module are shown in the following table.

Tempfile Module Function Function Description
tempfile.TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None) Create temporary files. This function returns a file-like object, which supports file I / O.
tempfile.NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True) Create temporary files. The function of this function is roughly the same as the previous function, except that the temporary file it generates has a file name in the file system.
tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None) Create temporary files. Compared with the TemporaryFile function, when the program outputs data to the temporary file, it will first output to memory, and will not actually output to the physical disk until it exceeds max_size.
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None) Generate a temporary directory.
tempfile.gettempdir() Get the system's temporary directory.
tempfile.gettempdirb() Same as gettempdir(), except that the function returns a byte string.
tempfile.gettempprefix() Returns the prefix name used to generate the temporary file.
tempfile.gettempprefixb() Same as gettempprefix (), except that the function returns a byte string.

The tempfile module also provides two low-level functions, tempfile.mkstemp () and tempfile.mkdtemp (). The four functions described above for creating temporary files and temporary directories are high-level functions. High-level functions support automatic cleanup and can be used with the with statement. These two low-level functions are not supported. Therefore, it is generally recommended to use high-level functions to create temporary files and temporary directories.

In addition, the tempfile module also provides the tempfile.tempdir property. You can change the system's temporary directory by assigning a value to this property.

The following program demonstrates how to use temporary files and temporary directories:

import tempfile
# Create temporary file
fp = tempfile.TemporaryFile ()
print (
fp.write ('Python Website,' .encode ('utf-8'))
fp.write ('shows some tutorials.'. encode ('utf-8'))
# Move the file pointer to the beginning, ready to read the file (0)
print ( (). decode ('utf-8')) # print the content just written
# Close the file, the file will be deleted automatically
fp.close ()
# Create a temporary file with the with statement, with will automatically close the temporary file
with tempfile.TemporaryFile () as fp:
    # Write content
    fp.write (b'I Love Python! ')
    # Move the file pointer to the beginning, ready to read the file (0)
    # Read file contents
    print ( ()) # b'I Love Python! '
# Create a temporary directory with the with statement
with tempfile.TemporaryDirectory () as tmpdirname:
    print ('Create temporary directory', tmpdirname)

The output is:

Python Website,shows some tutorials.
b'I Love Python! '
Create temporary directory C:\Users\LIM~1.JOU\AppData\Local\Temp\tmpaivr821d

The above program creates temporary files in two ways:

The first method is to manually create a temporary file. After reading and writing the temporary file, you need to actively close it. When the program closes the temporary file, the file will be automatically deleted.

The second way is to use a with statement to create a temporary file so that the with statement automatically closes the temporary file.

The above program also finally created a temporary directory. Because the program uses a with statement to manage the temporary directory, the program also automatically deletes the temporary directory.

The output of the first line above is the file name of the temporary file generated by the program, and the output of the last line is the directory name of the temporary directory generated by the program. It should be noted that do not look for temporary files or temporary folders, because the temporary files and temporary folders will be deleted when the program exits.


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises