Python压缩和解压缩文件(zip/unzip)

pythoner 分享于 16分钟前 25328阅 0人收藏此代码, 我要收藏

通过zipfile模块实现对文件、文件夹的zip压缩和解压

#打包成zip文件
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
f.write('file_to_add.py')
f.close()

#从zip文件解包
import zipfile
zfile = zipfile.ZipFile('archive.zip','r')
for filename in zfile.namelist():
    data = zfile.read(filename)
    file = open(filename, 'w+b')
    file.write(data)
    file.close()

#把整个文件夹内的文件打包
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
startdir = "c:\\mydirectory"
for dirpath, dirnames, filenames in os.walk(startdir):
    for filename in filenames:
        f.write(os.path.join(dirpath,filename))
f.close()
#该代码片段来自于: http://www.sharejs.com/codes/python/210

标签:
  • python压缩
  • python解压
  • zip