简体   繁体   中英

Zip all the files of a folder in the same folder

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.

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM