Advertisement
mengyuxin

meng.backupZIP.py

Jan 3rd, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. #! python3
  2. # backupZIP.py - copies an entrie folder and it's contencts into a ZIP file whose filename increments.
  3.  
  4. import zipfile
  5. import os
  6.  
  7. def backupToZip(folder):
  8.     # Backup the entire contencts of "folder" into a ZIP file.
  9.     folder = os.path.abspath(folder) # make sure foler is absolute
  10.  
  11.     # Figure out the filename this code should use based on what files already exist.
  12.     number = 1
  13.     while True:
  14.         zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
  15.         if not os.path.exists(zipFilename):
  16.             break
  17.         number += 1
  18.  
  19.     # Create the ZIP file.
  20.     print('Creating %s...' % (zipFilename))
  21.     backupZip = zipfile.ZipFile(zipFilename, 'w')
  22.  
  23.     # Walk the entire folder tree and compress the files in each folder.
  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 # don't backup the backup ZIP files
  33.             backupZip.write(os.path.join(foldername, filename))
  34.     backupZip.close()
  35.     print('Done.')
  36.  
  37. backupToZip('D:\\Study\\myPython')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement