使用 python 从 zip 文件中删除路径
我有一个带有路径的 zip 文件。当我使用 python 解压文件并将其放入目标文件夹时,它会在目标文件夹内的路径中创建所有文件。
目标:d:\unzip_files zip 文件的路径和文件名为: \NIS\TEST\Files\tnt.png
会发生什么: d:\unzip_files\NIS\TEST\Files\tnt.png
有没有办法只解压缩 tnt.png文件到 d:\unzip_files?或者我是否必须阅读列表并移动文件,然后删除所有空文件夹?
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()
所以,这就是有效的..
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()
感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将文件作为二进制读取并转储怎么样?需要处理已有文件的情况。
How about reading file as binary and dump it? Need to deal cases where there is pre-existing file.