python学习-第七篇
程序员文章站
2022-05-31 17:32:33
...
"""
Version: 0.4
Author: freshbin
Date: 2019年8月20日
"""
import os
import time
import zipfile
# 需要备份的文件目录
source = 'E:/python/myexample/pythonExample/day001/test007Data/needBak'
# 存储的目录
target_dir= 'E:/python/myexample/pythonExample/day001/test007Data/bakDir'
# 如果目标目录还不存在,则进行创建
if not os.path.exists(target_dir):
os.mkdir(target_dir)
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
# zip文件名称格式
target = today + os.sep + now + '.zip'
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
def zip_dir(dirname,zipfilename):
filelist = []
if os.path.isfile(dirname):
print('dirname: {}'.format(dirname))
filelist.append(dirname)
else :
for root, dirs, files in os.walk(dirname):
for dir in dirs:
print('dir in dirs===root:{}, dir:{},dirs:{}'.format(root, dir, dirs))
filelist.append(os.path.join(root,dir))
for name in files:
print('name in files===root:{}, name:{}, files:{}'.format(root, name, files))
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for tar in filelist:
arcname = tar[len(dirname):]
print('需要压缩的文件:{}'.format(arcname))
zf.write(tar,arcname)
zf.close()
zip_dir(source, target)
上一篇: python压缩文件目录- 和 -解压缩目录(完美)
下一篇: react开发环境的搭建