19-第2步_创建新ZIP文件
第2步:创建新ZIP文件
接下来让我们创建ZIP文件。让你的程序看起来像这样:
#! python3
# backupToZip.py - Copies an entire folder and its contents into
# a ZIP file whose filename increments.
--snip--
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
# Create the ZIP file.
print(f'Creating {zipFilename}...')
❶ backupZip = zipfile.ZipFile(zipFilename, 'w')
# TODO: Walk the entire folder tree and compress the files in each folder.
print('Done.')
backupToZip('C:\\delicious')
既然新ZIP文件的文件名保存在 zipFilename
变量中,你就可以调用 zipfile.ZipFile()
实际创建这个ZIP文件❶了。确保传入 'w'
作为第二个参数,这样ZIP文件就会以写模式打开。