summaryrefslogtreecommitdiff
path: root/Chap9ProjBackupToZip.py
blob: e9f8e00bb9f8617bcc77368e01201ba4f4c677b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python3

# Chapter 9 Project Backup to Zip
# Copies a folder recursively into a zip file and names it incrementally.

import os
import zipfile

def backupToZip(folder):
    folder = os.path.abspath(folder)

    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1

    print('Creating %s...' % (zipFilename))
    backupZip = zipfile.ZipFile(zipFilename, 'w')

    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in ' + foldername + '...')
        backupZip.write(foldername)
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue
            backupZip.write(os.path.join(foldername, filename))
    
    backupZip.close()
    print('Done')


backupToZip('/Users/mlotspaih/Documents/waffle')