cafeKaze cafeKaze - 5 months ago 31
Python Question

Zipping a folder with os.walk

I'm trying to zip a folder and every contained subfolder and file using

os.walk()
, but I am having trouble removing the folder path to the root folder - meaning I would like to remove
D:\\Users\\Username\\Desktop
when opening up the zipfile, but instead open straight to the root folder.

I've been trying to use
os.path.basename()
and zipfile's
arcname
argument, but just can't seem to get it right:

def backupToZip(folder):

import zipfile, os

folder = os.path.abspath(folder) # make sure folder is absolute

# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):

# Add the current folder to the ZIP file.
backupZip.write(foldername)

# Add all the files in this folder to the ZIP file.
for filename in filenames:
backupZip.write(os.path.join(foldername, filename))
backupZip.close()

backupToZip('Sample Folder')

Answer

If you want to avoid chdir, which impacts the whole process, you can use relpath to get the relative path starting from your top folder.

You could use something like

def backupToZip(folder):

    import zipfile, os

    folder = os.path.abspath(folder) # make sure folder is absolute

    # Walk the entire folder tree and compress the files in each folder.  
    for foldername, subfolders, filenames in os.walk(folder):

        if foldername == folder:
             archive_folder_name = ''
        else:
             archive_folder_name = os.path.relpath(foldername, folder)

             # Add the current folder to the ZIP file.
             backupZip.write(foldername, arcname=archive_folder_name)

        # Add all the files in this folder to the ZIP file.
        for filename in filenames:
            backupZip.write(os.path.join(foldername, filename), arcname=os.path.join(archive_folder_name, filename))
    backupZip.close()

backupToZip('Sample Folder')