The lzma Module



The Lempel−Ziv−Markov chain algorithm (LZMA) performs lossless data compression using a dictionary compression scheme featuring a higher compression ratio than other compression algorithms. Python's lzma module consists of classes and convenience functions for compression and decompression of data with LZMA algorithm.

Although the functionality in this module is similar to that of bz2 module, the LZMAFile class is not thread safe as compared to BZ2File class.

Here again, open() function in lzma module is a very easiest way to open lzma-compressed file object.

open() function

This function opens a LZMA-compressed file and returns a file object. The function requires two main parameters − file name and mode. The mode parameter is by default "rb" but can take any of 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 given data using LZMA algorithm and returns a byte object. This function can optionally hava a format argument that decides the container format. Possible values are FORMAT_XZ (default) and FORMAT_ALONE.

decompress() function

This function decompresses the data and returns uncompressed byte object.

Above functions are used in following examples. To write LZMA compressed data to file −

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

A 'test.xz' file will be created in current working directory. To fetch uncompressed data from this file use following code −

import lzma
f=lzma.open("test.xz","rb")
data=f.read()
print (data)
b'Welcome to TutorialsPoint'

To perform compression using object oriented API of lzma module, we have to use LZMAFile class.

LZMAFile() method

This is the constructor for LZMAFile class. It requires file and mode to be specified. The object with 'w' or 'wb' mode makes write() method available to it.

write() method

This method compress given data and write it into the file underneath it.

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

The compressed file is read and uncompressed data is retrieved by read() method of LZMAFile object created with mode='rb' parameter.

read() function

This method reads data from compressed file and returns uncompressed data.

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