how to compress multiples files present in subfolders with their respective file's names. zip files should contain in respective sub folders

Question:

I am very new in python pls anyone tell me how to compress files present in subfolders respectively below is my code, but it won’t work can anyone guide me

import os
import zipfile

for folder, subfolders, files in os.walk('DATA'):

    for file in files:
        if file.endswith('.txt'):
            with zipfile.ZipFile(file[0:-4] + '.zip', 'w') as fzip:
                fzip.write(os.path.join(folder, file),
                                os.path.relpath(os.path.join(folder, file), 'DATA'),
                                compress_type=zipfile.ZIP_DEFLATED)

.txt file path:-  
DATA1AA.txt 
DATA2AB.txt 
DATA3AC.txt
DATA4AD.txt 
DATA5AE.txt 
DATA6AF.txt 
DATA7AG.txt

zip file should be created in: -

D:DATA1AA.txt & AA.zip 
D:DATA2AB.txt & AB.zip 
D:DATA3AC.txt & AC.zip 
D:DATA4AD.txt & AD.zip 
D:DATA5AE.txt & AE.zip
D:DATA6AF.txt & AF.zip 
D:DATA7AG.txt & AG.zip
Asked By: Chetan

||

Answers:

If I understood your problem correctly, the .zip files weren’t being saved into the same directories as the .txt files. The following code should solve that issue for you. It combines the folder and file objects to create the new paths.

import os
import zipfile

for folder, subfolders, files in os.walk('DATA'):
    for file in files:
        if file.endswith('.txt'):
            # specify path of zip file: Split by "." and take first item to remove the ".txt"
            zip_path = os.path.join(folder, file.replace(".txt", ".zip"))
            with zipfile.ZipFile(zip_path, 'w') as fzip:
                fzip.write(
                    os.path.join(folder, file),
                    os.path.relpath(os.path.join(folder, file), 'DATA'), 
                    compress_type=zipfile.ZIP_DEFLATED
                )

In the future I’d recommend using glob to fix this. glob avoids the separation of the directories and files.

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.