Python lzma module

Python lzma Module

LZMA (Lempel–Ziv–Markov chain algorithm) is a lossless data compression algorithm that uses a dictionary compression scheme, achieving higher compression ratios than other compression algorithms. Python’s lzma module includes classes and convenience functions for compressing and decompressing data using the LZMA algorithm.

While this module’s functionality is similar to the bz2 module, the LZMAFile class is not thread-safe, unlike the BZ2File class.

Here, the open() function in the lzma module provides a simple way to open an LZMA-compressed file object.

open() Function

This function opens an LZMA-compressed file and returns a file object. The function requires two main parameters: the file name and the mode. The mode parameter defaults to “rb” but can take any of the following values:

Binary Mode – “r”, “rb”, “w”, “wb”, “x”, “xb”, “a”, or “ab”

Text Mode – “rt”, “wt”, “xt”, or “at”

compress() Function

This function compresses the given data using the LZMA algorithm and returns a bytes object. This function optionally takes a format parameter, which determines the container format. Possible values are FORMAT_XZ (the default) and FORMAT_ALONE.

decompress() Function

This function decompresses the data and returns the decompressed bytes object.

The above function is used in the following examples. To write LZMA-compressed data to a file:

import lzma
data=b”Welcome to TutorialsPoint”
f=lzma.open(“test.xz”,”wb”)
f.write(data)
f.close()

pre>

This will create a “test.xz” file in the current working directory. To retrieve uncompressed data from this file, use the following code:

import lzma
f=lzma.open(“test.xz”,”rb”)
data=f.read()
print(data)
b’Welcome to TutorialsPoint’

pre>

When performing compression using the lzma module’s object-oriented API, we must use the LZMAFile class.

LZMAFile() Method

This is the constructor for the LZMAFile class. It requires a file and a mode. Objects with mode ‘w’ or ‘wb’ can use the write() method.

write() Method

This method compresses the given data and writes it to the file below it.

data=b'Welcome to TutorialsPoint'
obj=lzma.LZMAFile("test.xz", mode="wb")
obj.write(data)
obj.close()

The read() method of an LZMAFile object created with the mode=’rb’ parameter reads the compressed file and retrieves the decompressed data.

read() Function

This method reads data from the compressed file and returns the decompressed data.

obj=lzma.LZMAFile("test.xz", mode="rb")
data=obj.read()
data
b'Welcome to TutorialsPoint'

Leave a Reply

Your email address will not be published. Required fields are marked *