Python:将文件解压缩到当前工作目录,但不保存zip中的目录结构
发布时间:2020-12-20 11:26:51 所属栏目:Python 来源:网络整理
导读:我有一个像这样的zip文件: myArchive.zip|-folder1 | --folder2 | ---myimage.jpg 当我尝试提取myimage.jpg时: with zipfile.ZipFile('myArchive.zip','r') as zfile: zfile.extract('folder1/folder2/myimage.jpg') 我将在我当前工作的目录中获得/folder1
我有一个像这样的zip文件:
myArchive.zip | -folder1 | --folder2 | ---myimage.jpg 当我尝试提取myimage.jpg时: with zipfile.ZipFile('myArchive.zip','r') as zfile: zfile.extract('folder1/folder2/myimage.jpg') 我将在我当前工作的目录中获得/folder1/folder2/myimage.jpg 但我只想将myimage.jpg提取到当前工作目录,我该怎么办呢? 解决方法
而不是使用extract或extractall,只需获取数据并将其写入您喜欢的任何文件.这是一个代码示例,可以满足您的需求:
import os,sys,time import zipfile ENC = 'cp437' outdir = unicode(os.path.abspath('.')) outzip = 'c:/1temp/timbersales.zip' zf = zipfile.ZipFile(outzip,'r') for info in zf.infolist(): fn,dtz = info.filename,info.date_time #,info.file_size # some zips have dirs listed as files. Catch # and bypass those. name = os.path.basename(fn) if not name: continue # get our filename converted from bytes to unicode fn_uni = fn.decode(ENC,'replace') bn_uni = os.path.basename(fn_uni) # this method is about 15% faster than extractall,and # preserves modify and access dates c = zf.open(fn) outfile = os.path.join(outdir,bn_uni) # try/except to avoid problems with locked files,etc # do in chunks to avoid memory problems chunk = 2**16 try: with open(outfile,'wb') as f: s = c.read(chunk) f.write(s) while not len(s) < chunk: s = c.read(chunk) f.write(s) c.close() # set modify and access dates to that inside the zip dtout = time.mktime(dtz + (0,-1)) os.utime(outfile,(dtout,dtout)) except IOError: c.close() 此示例执行zip中的所有文件,但您可以轻松添加几行来检查特定文件.它还将覆盖工作目录中的任何文件,其名称与提取的文件同名. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- python – 子命令中选项的argparse冲突解析器将关键字参数转
- python – 如何使我的SWIG扩展模块与Pickle工作?
- python – 在SCons中创建混合(值集)CPPDEFINES
- 如何在python中使用ctypes重载C库的弱声明函数?
- python dijkstra 最短路算法示意代码
- python – 当一个回调输入到Tkinter Entry Box的show参数时
- python – 当不重复生成列标题时,如何将csv文件作为MultiIn
- Python界的倚天剑和屠龙刀!最牛的两款编辑器!PyCharm和Ju
- Python GUI开发工具选择示例
- python根据出生日期计算年龄的代码