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

18-第1步_弄清楚ZIP文件的名称

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

第1步:弄清楚ZIP文件的名称

这个程序的代码将放在一个名为 backupToZip() 的函数中。这样就更容易将该函数复制粘贴到其他需要这个功能的Python程序中。这个程序的末尾会调用这个函数进行备份。让你的程序看起来像这样:

  #! python3
  # backupToZip.py - Copies an entire folder and its contents into
  # a ZIP file whose filename increments.
❶ import zipfile, os
  def backupToZip(folder):
      # Back up 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  =  number  +  1
   ❹  # TODO: Create the ZIP file.
      # TODO: Walk the entire folder tree and compress the files in each folder. 
      print('Done.')
  backupToZip('C:\\delicious')

先完成基本任务:添加#!行,描述该程序做什么,并导入 zipfileos 模块❶。

定义 backupToZip() 函数,它只接收一个参数,即 folder 。这个参数是一个字符串路径,指向需要备份的文件夹。该函数将决定它创建的ZIP文件使用什么文件名,然后创建该文件,遍历 folder 文件夹,并将每个子文件夹和文件添加到ZIP文件中。在源代码中为这些步骤写下 TODO 注释,提醒你稍后来完成❹。

第一部分是命名这个ZIP文件,使用 folder 的绝对路径的基本名称。如果要备份的文件夹是C:\delicious,那么ZIP文件的名称就应该是delicious_N.zip,第一次运行该程序时N=1,第二次运行时N=2,以此类推。

检查delicious_1.zip是否存在,然后检查delicious_2.zip是否存在,继续下去,可以确定N应该是什么。用一个名为 number 的变量表示N❷,在一个循环内不断增加它,并调用 os.path.exists() 来检查该文件是否存在❸。第一个不存在的文件名将导致循环 break ,从而它就发现了新ZIP文件的文件名。