zip and unzip files in python

  1. zip files
  2. unzip files
using `zipfile` modules in python can easy to zip or unzip files

zip files

Use the following codes can zip folds and files.

1
2
3
4
5
6
7
8
9
def zip_file(src_dir,filename):
zip_name = filename
z = zipfile.ZipFile(zip_name,'w',zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(src_dir):
fpath = dirpath.replace(src_dir,'')
fpath = fpath and fpath + os.sep or ''
for filename in filenames:
z.write(os.path.join(dirpath, filename),fpath+filename)
z.close()

src_dir:the path of fold that need to zip,filename:path and name to save the zip result.

unzip files

1
2
3
zipFile = zipfile.ZipFile("zip_filename")
zipFile.extractall("path_to_result")
zipFile.close()

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 jaytp@qq.com

文章标题:zip and unzip files in python

本文作者:子非鱼

发布时间:2019-05-07, 14:12:38

最后更新:2019-05-07, 14:24:48

原始链接:https://Wangsr.cn/2019/05/07/zip-and-unzip-files-in-python/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏