Created
December 10, 2012 10:28
-
-
Save dulichan/4249821 to your computer and use it in GitHub Desktop.
Create a backup zip of a folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import zipfile | |
import sys | |
import os, datetime | |
def zip_folder(folder_path, output_path): | |
"""Zip the contents of an entire folder (with that folder included | |
in the archive). Empty subfolders will be included in the archive | |
as well. | |
""" | |
parent_folder = os.path.dirname(folder_path) | |
# Retrieve the paths of the folder contents. | |
contents = os.walk(folder_path) | |
try: | |
zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) | |
for root, folders, files in contents: | |
# Include all subfolders, including empty ones. | |
for folder_name in folders: | |
absolute_path = os.path.join(root, folder_name) | |
relative_path = absolute_path.replace(parent_folder + '\\', | |
'') | |
print "Adding '%s' to archive." % absolute_path | |
zip_file.write(absolute_path, relative_path) | |
for file_name in files: | |
absolute_path = os.path.join(root, file_name) | |
relative_path = absolute_path.replace(parent_folder + '\\', | |
'') | |
print "Adding '%s' to archive." % absolute_path | |
zip_file.write(absolute_path, relative_path) | |
print "'%s' created successfully." % output_path | |
except IOError, message: | |
print message | |
sys.exit(1) | |
except OSError, message: | |
print message | |
sys.exit(1) | |
except zipfile.BadZipfile, message: | |
print message | |
sys.exit(1) | |
finally: | |
zip_file.close() | |
## TEST ## | |
if __name__ == '__main__': | |
today = datetime.datetime.now() | |
date = str(today.year)+'-'+str(today.month)+'-'+str(today.day) | |
print(date) | |
#Backup location | |
path = "G:/Archive/"+date+"/" | |
if not os.path.exists(path): os.makedirs(path) | |
## Folder to backup | |
orginialPath = 'F:/Workspace/Code7' | |
zip_folder(orginialPath, | |
path+"Code7(H"+str(today.hour)+").zip") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment