如何使用Python通过HTTP从远程Zip存档中读取所选文件? [英] How do I read selected files from a remote Zip archive over HTTP using Python?
问题描述
我需要使用Python从远程zip存档中读取与文件名匹配的所选文件。我不想将完整的zip保存到临时文件中(它不是那么大,所以我可以处理内存中的所有内容)。
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).
我已经写过代码,它的工作原理,我自己回答这个问题,以便我以后可以搜索它。但由于有证据表明我是Stackoverflow上的笨蛋参与者之一,我确信还有改进的余地。
I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.
推荐答案
我是这样做的(抓住所有以.ranks结尾的文件):
Here's how I did it (grabbing all files ending in ".ranks"):
import urllib2, cStringIO, zipfile
try:
remotezip = urllib2.urlopen(url)
zipinmemory = cStringIO.StringIO(remotezip.read())
zip = zipfile.ZipFile(zipinmemory)
for fn in zip.namelist():
if fn.endswith(".ranks"):
ranks_data = zip.read(fn)
for line in ranks_data.split("\n"):
# do something with each line
except urllib2.HTTPError:
# handle exception
这篇关于如何使用Python通过HTTP从远程Zip存档中读取所选文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!