Search code examples
pythonpython-3.xpython-zipfile

How to put files in a zip archive using Python zipfile


I wrote a python(3.5) script that creates backup of my files in zip archive and it works well. I use windows and I installed zip command from GnuWin32 for this project. But I want to use Python's Zipfile library instead. How can I modify my code?

import os
import time
import sys

source = 'C:\\ExampleFile'

target_directory ='D:\\BACKUP'

confirm = input("Are you sure you want to run backup? (y/n): ")

if confirm == "y":
    if not os.path.exists(target_directory):
        os.mkdir(target_directory)

    Folder = target_directory + os.sep + time.strftime('%d-%m-%Y')
    Subfolder = time.strftime('%H-%M')

    comment = input('Enter a backup comment (optional):  ')

    if len(comment) == 0:
        target = Folder + os.sep + Subfolder + '.zip'
    else:
        target = Folder + os.sep + Subfolder + '_' + comment.replace(' ', '_') + '.zip'
    if not os.path.exists(today):
        os.mkdir(Folder)
        print('Successfully created directory', Folder)

    zip_command = "zip -r {0} {1}".format(target,''.join(source))

    print("Running:")
    if os.system(zip_command) == 0:
        print('\nSuccessful backup to', target)
    else:
        print('\nBackup FAILED')

elif confirm == "n":
    sys.exit()
else:
    print("Use only 'y' or 'n'")

Solution

  • This might be a good start:

    #!/usr/bin/python
    import zipfile, os
    
    def zipdir(path, fname="test.zip"):
        zipf = zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED)
        for root, dirs, files in os.walk(path):
            for file in files:
                zipf.write(os.path.join(root, file))
        zipf.close()