Python ZipFile and Suppress Creating Zip File if Directory is Empty

60 Views Asked by At

Attempting to zip a directory for further file processing. I am able to successfully zip and move the file as expected. However, if the directory does not contain any files, the ZipFile process is still creating an empty ZipFile. My requirements are to only create a zip file if there are files present in said directory.

Thanks in advance for any help and assistance!

# STEP 3 - Create ZipFile
zip_path = 'E:/GL/download_ceridian/ceridian.zip'
directory_to_zip =  'E:/GL/download_ceridian'

folder = pathlib.Path(directory_to_zip)
filelist = list(folder.iterdir())

with ZipFile(zip_path, 'w' , ZIP_DEFLATED) as zip:
    for file in filelist:
        zip.write(file , arcname=file.name)
1

There are 1 best solutions below

0
JonSG On

You likely want to just guard for the times that there are no files:

# STEP 3 - Create ZipFile
zip_path = 'E:/GL/download_ceridian/ceridian.zip'
directory_to_zip =  'E:/GL/download_ceridian'

folder = pathlib.Path(directory_to_zip)
filelist = list(folder.iterdir())

if filelist:
    # filelist is not an empty list...
    with ZipFile(zip_path, 'w' , ZIP_DEFLATED) as zip:
        for file in filelist:
            zip.write(file , arcname=file.name)