Python:从url获取zip文件,解压缩并将文件/图像保存到服务器

时间:2014-11-16 14:04:57

标签: python python-imaging-library zipfile

我从网址获取了一个zipfile。

提取,它具有以下格式:

  • parent_folder
    • my_file.csv文件
    • image_folder
      • my_image.jpg

我想将此提取保存到我的服务器。在保存之前,我想1)更改parent_folder的名称,2)在.csv文件中插入额外的文本

我尝试了各种代码组合,试图弄清楚发生了什么:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
from PIL import Image

url = urlopen("path.zip")
z = ZipFile(StringIO(url.read()))

# z= z.extractall() # not sure I need this?

for line in z.open("my_file.csv").readlines():
     print line  
     # this does print so I could open a new file and write to it. Is that what I do?

img= Image.open(cStringIO.StringIO(z.open("image_folder/my_image.jpg")))
# error: must be convertible to a buffer, not ZipExtFile
# I don't know how to GET the image

1 个答案:

答案 0 :(得分:0)

原因:z.open("image_folder/my_image.jpg")提供了ZipExtFile个对象,而cStringIO.StringIO想要一个缓冲区。

解决方案:试试这个:

img= Image.open(cStringIO.StringIO(z.open("image_folder/my_image.jpg").read()))