Compressing files with python (bzip2, zip, lzma)

There are two main ways of compressing files/directories using python, below are some example code that you can use for bzip2, zip and lzma.

ZipFile

From file list:

import bz2
from zipfile import ZipFile
from zipfile import ZIP_BZIP2

file_list = ["file_1.txt", "file_2.txt"]
if __name__ == '__main__':
    with ZipFile(file='dict.bz2', mode='w', compression=ZIP_BZIP2) as zip:
        for path in file_list:
            zip.write(path)

Directory:

import bz2
import os
from zipfile import ZipFile
from zipfile import ZIP_BZIP2

if __name__ == '__main__':
    with ZipFile(file='dict.bz2', mode='w', compression=ZIP_BZIP2) as zip:
        for root, directories, files in os.walk("/path/goes/here"):
            zip.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..')))

To change method replace to the lines below:

import zlib
from zipfile import ZIP_DEFLATED
with ZipFile(file='dict.zip', mode='w', compression=ZIP_DEFLATED) as zip:
import bz2
from zipfile import ZIP_BZIP2
with ZipFile(file='dict.bz2', mode='w', compression=ZIP_BZIP2) as zip:
import lzma
from zipfile import ZIP_LZMA 
with ZipFile(file='dict.xz', mode='w', compression=ZIP_LZMA) as zip:

Shutil – Directory

import shutil
import bz2
shutil.make_archive("output name", "bztar", "directory/path/here") 

gztar or zip (import zlib)
bztar (import bz2)
xztar (import lzma)