Advertisement
Guest User

backup_to_zip.py

a guest
Apr 26th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. #! python3
  2. # backup_to_zip.py - copies an entire folder and its contents
  3. # to a zip file whose filename increments
  4.  
  5. import zipfile, os
  6.  
  7. def backup_to_zip(folder):
  8.     # backup the entire contents of "folder" into a ZIP file.
  9.  
  10.     folder = os.path.abspath(folder)  # make sure folder is absolute
  11.  
  12.     # figure out what filename this code should use
  13.     # based on what files already exist
  14.     number = 1
  15.     while True:
  16.         zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
  17.         if not os.path.exists(zipFilename):
  18.             break
  19.         number = number + 1
  20.  
  21.     # create the ZIP file
  22.     print('Creating %s...' % (zipFilename))
  23.     backupZip = zipfile.ZipFile(zipFilename, 'w')
  24.  
  25.     # Walk the entire folder tree and compress the files in each fodler
  26.     for foldername, subfolders, filenames in os.walk(folder):
  27.         print('Adding files in %s...' % (foldername))
  28.         # Add the current folder to the ZIP file
  29.         backupZip.write(foldername)
  30.  
  31.         # Add all the files in this folder to the ZIP file.
  32.         for filename in filenames:
  33.             newBase / os.path.basename(folder) + '_'
  34.             if filename.startswith(newBase) and filename.endswith('.zip')
  35.                 continue    # Don't backup the backup ZIP files.
  36.             backupZip.write(os.path.join(foldername, filename))
  37.     backupZip.close()
  38.     print('Done.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement