使用python从zip文件中删除路径

使用python从zip文件中删除路径

本文介绍了使用python从zip文件中删除路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带路径的zip文件.当我使用python解压缩文件并将其放在目标文件夹中时,它将在目标文件夹内的路径中创建所有文件.

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.

目标:d:\ unzip_files压缩文件的路径和文件名为:\ NIS \ TEST \ Files \ tnt.png

Target: d:\unzip_fileszip file has a path and file name of: \NIS\TEST\Files\tnt.png

会发生什么:d:\ unzip_files \ NIS \ TEST \ Files \ tnt.png

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

是否有办法将tnt.png文件解压缩到d:\ unzip_files中?还是我必须阅读列表并移动文件,然后删除所有空文件夹?

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()

感谢您的帮助.

推荐答案

如何将文件读取为二进制文件并将其转储?需要处理已有文件的情况.

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))

这篇关于使用python从zip文件中删除路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:31