larsmrx

BackupZipFile

Oct 7th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. #! python3
  2. #! backs folder up to a zip file and the version nr increments everytime its created
  3.  
  4. import zipfile, os
  5.  
  6. def backupToZip(folder):
  7.     folder = os.path.abspath(folder)
  8.  
  9.     number = 1
  10.     while True:
  11.         zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
  12.         if not os.path.exists(zipFilename):
  13.             break
  14.         number += 1
  15.  
  16. #TODO - Create a zip file
  17.  
  18.     print('Creating the %s ...' % (zipFilename))
  19.     backupZip = zipfile.ZipFile(zipFilename, 'w')
  20.  
  21.  
  22. #todo - Walk the entire folder and comporess the files in each folder
  23.  
  24.     for foldername, subfolders, filenames in os.walk(folder):
  25.         print(('Adding files in %s...') % (foldername))
  26.     #add the current folder to the ZIP file
  27.         backupZip.write(foldername)
  28.     #add all the files in this folder to the zip file
  29.         for filename in filenames:
  30.                 newBase = os.path.basename(folder) + '_'
  31.                 if filename.startswith(newBase) and filename.endswith('.zip'):
  32.                     continue # dont backup the backup zip files
  33.                 backupZip.write(os.path.join(foldername, filename))
  34.     backupZip.close()
  35.     print('done')
  36.  
  37. backupToZip('Downloads')
Add Comment
Please, Sign In to add comment