[英]Unzipping with specific name
Based on this answer , is there an option to rename the file when extracting it? 基于this answer ,提取文件时是否有重命名文件的选项? Or what is the best solution to do so?
或者这样做的最佳解决方案是什么?
Didn't find anything on the documentation在文档中没有找到任何内容
I found two methods:我找到了两种方法:
Using ZipFile.read()使用ZipFile.read()
You can get data from zip file using ZipFile.read()
and write it with new name
using standard open()
, write()
您可以使用
ZipFile.read()
从 zip 文件中获取数据,并使用标准open()
、 write()
用new name
写入它
import zipfile z = zipfile.ZipFile('image.zip') for f in z.infolist(): data = z.read(f) with open('new_name.png', 'wb') as fh: fh.write(data)
Using zipfile.extract() with ZipInfo将zipfile.extract()与ZipInfo一起使用
You can change name before using extract()
您可以在使用
extract()
之前更改名称
import zipfile z = zipfile.ZipFile('image.zip') for f in z.infolist(): #print(f.filename) #print(f.orig_filename) f.filename = 'new_name.png' z.extract(f)
This version can automatically create subfolders if you use如果您使用此版本可以自动创建子文件夹
f.filename = 'folder/subfolder/new_name.png' z.extract(f) f.filename = 'new_name.png' z.extract(f, 'folder/subfolder')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.