'zipfile module in python to compress files

Can zipfile module be used to compress files to a 7z archive? I have to work with a set of csv files and I have been asked to 7zip these files. I wanted to know if zipfile module in python would compress these files to 7z archive.



Solution 1:[1]

Zipfile does not compress to 7zip archives. You can write :

with ZipFile('archive.7z', 'w'):

it will create the archive, no problem, but you cannot decompress it like a .7z, it's still a .zip (structurally) with the wrong extension at the end.

Solution 2:[2]

Zipfile does not support the compression method used by default in the 7zip file format, LZMA. However, you can use community provided bindings to compress a file with LZMA. Install the pylzma library to your python environment. Once the module is installed, it is pretty straight forward to compress a file.

import pylzma
compressed = pylzma.compress(my_csv.csv)

The compressed file should be acceptable for 7zip. Usage docs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Appa21
Solution 2 Nathan