3

テキスト ファイルの 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)
4

3 に答える 3

5

あなたの答えはあなたのサンプルコードにあります。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)
于 2009-12-18T17:46:21.387 に答える
1

次のように言えます。

handler_dispatch(logfile)

def handler_dispatch(file):
   for line in file:
      handler1(line)
      handler2(line)

または、複数の handlerN 関数を使用して Handler クラスを構築し、それぞれを 内に適用することで、より動的にすることもできます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)
于 2009-12-18T17:40:37.453 に答える
1

zip ファイルを 1 回開き、すべての名前をループして、名前ごとにファイルを抽出して処理し、ディスクに書き込みます。

そのようです:

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)

あなたはアイデアを得る

于 2009-12-18T17:41:50.007 に答える