-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackupToZip.py
More file actions
68 lines (34 loc) · 1.62 KB
/
backupToZip.py
File metadata and controls
68 lines (34 loc) · 1.62 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#! python3
# backupToZip.py - Copies an entire folder and its contents into
# a ZIP file whose filename increments
import zipfile
import os
def backupToZip(folder):
# Backup the entire contents of 'folder' into a ZIP file
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should use based on
# what files already exist
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number += 1
# Create the zip file
print('Creating %s..' %(zipFilename))
backupZip = zipfile.ZipFile(zipFilename,'w')
# Walk the entire folder tree and compress the files in each folder.
for foldername,subfolders,filenames in os.walk(folder):
print('Adding files in %s ' %(foldername))
# add the current folder to the ZIP file
backupZip.write(foldername)
# add all the files in this folder to the ZIP file
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername,filename))
backupZip.close()
print('Done.')
os.chdir('source_path') # Change directory to the folder that needs to be backed
backupToZip('destination_path') # Saves ZIP file (backup) in the path specified