首页 > 编程知识 正文

python open打开文件,zipfile python

时间:2023-05-06 05:52:50 阅读:17604 作者:1773

希望将文件从zip文件提取到特定路径,并忽略归档文件中的文件路径。 这在Python2.6上非常简单。 (我的文档比代码长。 )导入套件

导入zipfile

efextract_from_zip(name,dest_path,zip_file ) :

' ' ' similartozipfile.zipfile.extractbutextractsthefilegivenbyname

来自the zip _ file (instance of zipfile.zipfile ) ) to the given dest_path

* ignoring * thefilenamepathgiveninthearchivecompletely

insteadofpreservingitasextractdoes。

''''

dest_file=open(dest_path,' wb ' ) )。

archived _ file=zip _ file.open (name )

shutil.copyfile obj (archived _ file,dest_file ) ) ) ) ) ) ) )。

extract _ from _ zip (' path/to/file.dat '、' output.txt '、zipfile.zipfile('test.zip '、' r ' ) )

但是,在Python2.5中不能使用ZipFile.open方法。 找不到堆栈溢出解决方案,但this forum post有很好的解决方案。 它使用^{}查找zip的正确点,然后使用^{}从那里解压缩字节。 不幸的是,ZipInfo.file_offset在python2.5中被删除了! 在

因此,考虑到Python2.5中只有^{},我认为您可以通过分析和跳过标头结构来自行获取文件偏移。 使用维基作为a reference,我想出了一个长得多、不太优雅的解决方案。 在

^{pr2}$

请注意,如果对ZipInfo.extra属性调用len,它将减少4个字节,并导致偏移计算错误,因此如何解压缩和读取具有附加字段长度的字段。 我可能遗漏了什么吗? 在

有人能改进这个Python2.5的解决方案吗? 在

编辑:应该说是ChrisAdams建议的显而易见的解决方案dest_file.write(zip_file.read ) name )。

对于zip中包含的大小合适的文件,内存错误将失败,因为它尝试一次将整个文件提取到内存中。 因为有很大的文件,所以需要将内容流式传输到磁盘。 在

另外,升级Python是一个明显的解决方案,但这在我的控制中完全没有,基本上是不可能的。 在

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。