python逐个读取文件_在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來緩沖日志文件:
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)
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python逐个读取文件_在Python中多次读取同一文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: messagebox 全部使用_「一」W
- 下一篇: python不需要缩进的代码顶行编写_p