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

20-第3步_遍历目录树并添加到ZIP文件

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

第3步:遍历目录树并添加到ZIP文件

现在需要使用 os.walk() 函数列出文件夹以及子文件夹中的每个文件。让你的程序看起来像这样:

#! python3
# backupToZip.py - Copies an entire folder and its contents into
# a ZIP file whose filename increments.
--snip--
 # Walk the entire folder tree and compress the files in each folder.
 ❶ for foldername, subfolders, filenames in os.walk(folder): 
 print(f'Adding files in {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 back up the backup ZIP files
 backupZip.write(os.path.join(foldername, filename)) 
backupZip.close()
     print('Done.')
backupToZip('C:\\delicious')

可以在 for 循环中使用 os.walk() ❶,在每次迭代中,它将返回这次迭代当前的文件夹名称、这个文件夹中的子文件夹,以及这个文件夹中的文件名。

在这个 for 循环中,该文件夹被添加到ZIP文件❷。嵌套的 for 循环将遍历 filenames 列表中的每个文件❸。每个文件都被添加到ZIP文件中,以前生成的备份ZIP文件除外。

如果运行该程序,它产生的输出结果看起来像这样:

Creating delicious_1.zip...
Adding  files in C:\delicious...
Adding  files in C:\delicious\cats...
Adding  files in C:\delicious\waffles...
Adding  files in C:\delicious\walnut...
Adding  files in C:\delicious\walnut\waffles...
Done.

第二次运行它时,它将C:\delicious中的所有文件放进一个ZIP文件,并将其命名为delicious_2.zip,以此类推。