题
我需要下载文本文件的zip存档,将存档中的每个文本文件派遣到其他处理程序进行处理,最后将未拉链的文本文件写入磁盘。
我有以下代码。它在同一文件上使用多个打开/关闭,这似乎并不优雅。如何使其更优雅和高效?
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
logfile = unzipped.open(f_info)
handler1(logfile)
logfile.close() ## Cannot seek(0). The file like obj does not support seek()
logfile = unzipped.open(f_info)
handler2(logfile)
logfile.close()
unzipped.extract(f_info)
解决方案
您的答案在您的示例代码中。只需使用Stringio来缓冲日志文件:
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
logfile = unzipped.open(f_info)
# Here's where we buffer:
logbuffer = cStringIO.StringIO(logfile.read())
logfile.close()
for handler in [handler1, handler2]:
handler(logbuffer)
# StringIO objects support seek():
logbuffer.seek(0)
unzipped.extract(f_info)
其他提示
您可以说类似:
handler_dispatch(logfile)
和
def handler_dispatch(file):
for line in file:
handler1(line)
handler2(line)
甚至通过构建具有多个处理程序的处理程序类,并将它们都应用到其中,甚至使其更具动态性 handler_dispatch
. 。喜欢
class Handler:
def __init__(self:)
self.handlers = []
def add_handler(handler):
self.handlers.append(handler)
def handler_dispatch(self, file):
for line in file:
for handler in self.handlers:
handler.handle(line)
打开一次zip文件,循环浏览所有名称,提取每个名称的文件并处理它,然后将其写入磁盘。
像这样:
for f_info in unzipped.info_list():
file = unzipped.open(f_info)
data = file.read()
# If you need a file like object, wrap it in a cStringIO
fobj = cStringIO.StringIO(data)
handler1(fobj)
handler2(fobj)
with open(filename,"w") as fp:
fp.write(data)
你明白了
不隶属于 StackOverflow