How to compress folders in 7z format using python

Viewed 18

I have a nested folder structure like:

 - Folder1  
     ---->Test1  
     -------->a  
     -------->b  
     -------->c  
- Folder2  
     ---->Test2  
     -------->d  
     -------->e  
     -------->f  
- Folder3  
     ---->Test3  
     -------->g  
     -------->h  
     -------->i

I want to create a 7zipped file named as Folder1.7z,Folder2.7z,,Folder3.7z...etc which upon extracting folders respectively.How to write python script for this thing to work??

Note:I want to use python only.

1 Answers

There is a useful library, py7zr, which supports 7zip archive compression, decompression, encryption and decryption.

import py7zr
with py7zr.SevenZipFile('Folder1.7z', mode='w') as z:
    z.writeall('./Folder1')

If you would like to automate it for n amount of folders you can do this.

import py7zr
n = 10
for i in range(n):
    with py7zr.SevenZipFile(f'Folder{i}.7z', mode='w') as z:
        z.writeall(f'./Folder{i}')
Related