代码之家  ›  专栏  ›  技术社区  ›  espenhogbakk

ZipFile抱怨道,有没有办法使用ZipFile模块?

  •  1
  • espenhogbakk  · 技术社区  · 17 年前

    这就是我得到的

    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模块会抱怨一些文件。

    我是否可以使用unix命令unzip而不是zipfile,然后使用相同的方法从存档中检索所有图像?

    2 回复  |  直到 17 年前
        1
  •  5
  •   unwind    17 年前

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

    zippedfile = open('%stemp/tempfile.zip' % settings.MEDIA_ROOT, 'wb+')
    
        2
  •  1
  •   Douglas Leeder    17 年前

    您可能需要关闭并重新打开文件,或者在写入文件后查找文件的开头。

    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')