当前位置:嗨网首页>书籍在线阅读

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文件就会以写模式打开。