python逐个读取文件_在Python中多次读取同一文件
我需要下載文本文件的zip存檔,將存檔中的每個(gè)文本文件分發(fā)給其他處理程序進(jìn)行處理,最后將解壓縮的文本文件寫入磁盤.
我有以下代碼.它在同一個(gè)文件上使用多個(gè)打開/關(guān)閉,這看起來(lái)并不優(yōu)雅.如何讓它更優(yōu)雅高效?
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來(lái)緩沖日志文件:
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位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python逐个读取文件_在Python中多次读取同一文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: messagebox 全部使用_「一」W
- 下一篇: application.properti