문제

텍스트 파일의 Zip Archive를 다운로드하고 처리를 위해 다른 핸들러로 아카이브의 각 텍스트 파일을 발송하고 최종적으로 압축 된 텍스트 파일을 디스크에 작성해야합니다.

다음 코드가 있습니다. 동일한 파일에서 여러 개 열고 닫기를 사용하여 우아하지 않은 것처럼 보입니다. 더 우아하고 효율적으로 만드는 방법은 무엇입니까?

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)

당신은 아이디어를 얻습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top