Python学习笔记组织文件之将一个文件夹备份到一个zip文件
随笔记录方便自己和同路人查阅。
#------------------------------------------------我是可耻的分割线-------------------------------------------
假定你正在做一个项目,它的文件保存在C:\AlsPythonBook 文件夹中。你担心工作会丢失,所以希望为整个文件夹创建一个ZIP 文件,作为“快照”。你希望保存
不同的版本,希望 ZIP 文件的文件名每次创建时都有所变化。例如 AlsPythonBook_1.zip、AlsPythonBook_2.zip、AlsPythonBook_3.zip,等等。你可以手工完成,
但这有点烦人,而且可能不小心弄错ZIP 文件的编号。运行一个程序来完成这个烦人的任务会简单得多。
#------------------------------------------------我是可耻的分割线-------------------------------------------
示例代码:
#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
#a ZIP file whose filename increments
import zipfile, 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 used 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
# 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:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('d:\\quiz')
运行结果:
会把传入的路径中所有内容,备份到当前工作目录中

浙公网安备 33010602011771号