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