Home > database >  Zip all the files of a folder in the same folder
Zip all the files of a folder in the same folder

Time:12-09

I am trying to zip all the files from a folder and places it in the same folder. Below is my code:

import os as __os
import zipfile

def zipdir(path, ziph):
    for root, dirs, files in __os.walk(path):
        for file in files:
            print(file)
            ziph.write(__os.path.join(root, file))


if __name__ == '__main__':
    zip_name = 'test.zip'
    working_directory = "C:\\Users\\Admin\\Downloads\\gaz"
    archive_name = __os.path.join(working_directory, zip_name)
    with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
        zipdir(working_directory   '', zipf)


I am trying to create zip of all the files inside a folder. I am expecting the code to create a zip in the same folder. Its going into infinite.

CodePudding user response:

I don't really see an endless loop but you're including the newly created test.zip (empty) to the archive of the same name.

It would be better to check file before adding it to the archive:

def zipdir(path, ziph):
    for root, dirs, files in __os.walk(path):
        for file in files:
            if file != zip_name:
                print(file)
                ziph.write(__os.path.join(root, file))

CodePudding user response:

The zipdir() funciton is calling itself recursively, resulting in the infinite loop. Try zipf.write(). That function adds a file to a zip archive.

with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in __os.walk(working_directory):
            for file in files:
                if os.path.samefile(archive_path, os.path.join(root, file)):
                    continue
                zipf.write(__os.path.join(root, file))

Edit: Check if archive_name file is located in working_directory

  • Related