【问题标题】:ZipFile complains, is there a way around using the zipfile module?ZipFile 抱怨,有没有办法使用 zipfile 模块?
【发布时间】:2010-10-04 00:51:23
【问题描述】:

我正在尝试解压缩一些压缩后发送给我的彩信。问题是有时它有效,而另一些则无效。当它不起作用时,python zipfile 模块会抱怨并说它是一个错误的 zip 文件。但是使用 unix unzip 命令解压的 zip 文件很好。

这就是我得到的

zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'w+')
zippedfile.write(string)
z = zipfile.ZipFile(zippedfile)

我正在使用 'w+' 并向其写入一个字符串,该字符串包含一个 zip 文件的 base64 解码字符串表示。

那我就这样了:

filelist = z.infolist()  
images = []  

for f in filelist:  
    raw_mimetype = mimetypes.guess_type(f.filename)[0]  
    if raw_mimetype:  
        mimetype = raw_mimetype.split('/')[0]  
    else:  
        mimetype = 'unknown'  
    if mimetype == 'image':  
        images.append(f.filename)  

这样我就得到了 zip 文件中所有图像的列表。但这并不总是有效,因为 zipfile 模块会抱怨某些文件。

有没有办法做到这一点,而不使用 zipfile 模块?

我能否以某种方式使用 unix 命令解压缩而不是 zipfile,然后使用同一件事从存档中检索所有图像?

【问题讨论】:

    标签: python zip popen zipfile


    【解决方案1】:

    您可能必须关闭并重新打开文件,或者在写入文件后寻找文件的开头。

    filename = '%stemp/tempfile.zip' % settings.MEDIA_ROOT
    zippedfile = open(filename , 'wb+')
    zippedfile.write(string)
    zippedfile.close()
    z = zipfile.ZipFile(filename,"r")
    

    你说字符串是 base64 解码的,但你没有显示任何解码它的代码 - 你确定它还没有编码吗?

    data = string.decode('base64')
    

    【讨论】:

    • 对不起,这没有帮助,当我尝试这样做时,我实际上得到一个错误,我无法对关闭的文件执行 I/O 操作。
    【解决方案2】:

    在将压缩数据写入文件时,您很可能应该以二进制模式打开文件。也就是说,你应该使用

    zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')
    

    【讨论】:

    • 对不起,这无济于事,它仍然抱怨 zipfile 错误。这并不奇怪,因为代码有时确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多