Backup data from a provided location to a zipped file in another location. Solution adapted from Automate the Boring Stuff with Python.
#! python2 # MyBackupScript.py - backup the My Documents folder and all contents into # a zip file whole filename increments import zipfile, shutil, os, sys #function to create the backup zip file def backupToZip(folder, location): # Backup the entire contents of "folder" into a zip file folder = os.path.abspath(folder) #make certain the path is an abs one # figure out the filename this code should use based on what files # already exist in location number = 1 while True: zipFilename = location + os.path.basename(folder) + '_' + str(number) + '.zip' if not os.path.exists(zipFilename): break number = number + 1 # set the filename zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip' # Create the zip file print('Creating %s...' % (zipFilename)) backupZip = zipfile.ZipFile(zipFilename, 'w') # Walk the entire folder tree and compress the files in each folder for foldername, subfolders, filenames in os.walk(folder): print('Adding files in %s...' % (foldername)) # 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: newBase = os.path.basename(folder) + '_' if filename.startswith(newBase) and filename.endswith('.zip'): continue # don't backup the backup zip files backupZip.write(os.path.join(foldername, filename)) backupZip.close() #move the file from the directory copied to given location shutil.move(zipFilename, (location + zipFilename)) print('Done.') # The Main body of the program; call the function backupToZip if len(sys.argv) != 3: print('Usage: py.exe MyBackupScript.py Dir_to_Copy Location_to_Store') sys.exit() backupToZip(sys.argv, sys.argv)