python压缩文件不带根路径,使用python从zip文件中删除路径

I have a zip file that has a path. When I unzip the file using python and put it in my target folder, it then creates all of the files in the path inside my target folder.

Target: d:\unzip_files

zip file has a path and file name of: \NIS\TEST\Files\tnt.png

What happens: d:\unzip_files\NIS\TEST\Files\tnt.png

Is there a way to hae it just unzip the tnt.png file into d:\unzip_files? Or will I have to read down the list and move the file and then delete all of the empty folders?

import os, sys, zipfile

zippath = r"D:\zip_files\test.zip"

zipdir = r"D:\unzip_files"

zfile = zipfile.ZipFile(zippath, "r")

for name in zfile.namelist():

zfile.extract(name, zipdir)

zfile.close()

So, this is what worked..

import os, sys, zipfile

zippath = r"D:\zip_files\test.zip"

zipdir = r"D:\unzip_files"

zfile = zipfile.ZipFile(zippath, "r")

for name in zfile.namelist():

fname = os.path.join(zipdir, os.path.basename(name))

fout = open(fname, "wb")

fout.write(zfile.read(name))

fout.close()

Thanks for the help.

解决方案

How about reading file as binary and dump it? Need to deal cases where there is pre-existing file.

for name in zfile.namelist():

fname = os.path.join(zipdir, os.path.basename(name))

fout = open(fname, 'wb')

fout.write(zfile.read(name))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值