Advertisement
Stosswalkinator

backupToZip.py

Feb 24th, 2017
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. #! python3
  2. # backupToZip.py - Copies an entire folder and its contents into
  3. # a ZIP file whose filename increments.
  4.  
  5. import zipfile, os
  6.  
  7. def backupToZip(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 the filename this code should use based on
  13.     # 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 folder.
  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.         # Add all the files in this folder to the ZIP file.
  31.         for filename in filenames:
  32.             newBase / os.path.basename(folder) + '_'
  33.             if filename.startswith(newBase) and filename.endswith('.zip'):
  34.                 continue # don't backup the backup ZIP files
  35.             backupZip.write(os.path.join(foldername, filename))
  36.     backupZip.close()
  37.     print('Done')
  38.  
  39. backupToZip('/home/lstoss/Documents/python_automate')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement