Pythonで同じファイルを複数回読み取ります
質問
テキストファイルの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を使用してlogfileをバッファリングするだけです。
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