使用python 2.4和內置的ZipFile
庫,我無法讀取非常大的zip文件(大於1或2 GB),因爲它想要將未壓縮文件的全部內容存儲在內存中。還有另一種方法可以做到這一點(無論是第三方庫還是其他黑客),還是我必須「掏空」並以這種方式解壓縮(顯然,這不是跨平臺的)。如何在python中解壓非常大的文件?
15
A
回答
16
下面是大文件解壓的概述。
import zipfile
import zlib
import os
src = open(doc, "rb")
zf = zipfile.ZipFile(src)
for m in zf.infolist():
# Examine the header
print m.filename, m.header_offset, m.compress_size, repr(m.extra), repr(m.comment)
src.seek(m.header_offset)
src.read(30) # Good to use struct to unpack this.
nm= src.read(len(m.filename))
if len(m.extra) > 0: ex= src.read(len(m.extra))
if len(m.comment) > 0: cm= src.read(len(m.comment))
# Build a decompression object
decomp= zlib.decompressobj(-15)
# This can be done with a loop reading blocks
out= open(m.filename, "wb")
result= decomp.decompress(src.read(m.compress_size))
out.write(result)
result = decomp.flush()
out.write(result)
# end of the loop
out.close()
zf.close()
src.close()
8
對於Python 2.6,你可以使用ZipFile.open()
打開一個文件句柄上的文件,有效的內容複製到您選擇的目標文件:
import errno
import os
import shutil
import zipfile
TARGETDIR = '/foo/bar/baz'
with open(doc, "rb") as zipsrc:
zfile = zipfile.ZipFile(zipsrc)
for member in zfile.infolist():
target_path = os.path.join(TARGETDIR, member.filename)
if target_path.endswith('/'): # folder entry, create
try:
os.makedirs(target_path)
except (OSError, IOError) as err:
# Windows may complain if the folders already exist
if err.errno != errno.EEXIST:
raise
continue
with open(target_path, 'wb') as outfile, zfile.open(member) as infile:
shutil.copyfileobj(infile, outfile)
這使用shutil.copyfileobj()
高效地閱讀來自打開的zipfile對象的數據,將其複製到輸出文件。
相關問題
- 1. PHP解壓縮非常大的文件
- 2. Python json解析非常大的文件
- 3. 解壓縮非常大的文件時出現問題
- 4. Python的解壓縮大文件 - NotImplementedError:98
- 5. 如何解析C#中非常龐大的XML文件?
- 6. 如何在壓縮文件中使用非ASCII文件名並在Python 2.4中使用ZipFile將其解壓縮?
- 7. 解析與Python非常大的HTML文件(ElementTree的?)
- 8. 如何在java中解壓非UTF8格式的文件
- 9. 解壓Z01,Z02,壓縮在Python文件
- 10. Python xml ElementTree能解析一個非常大的xml文件嗎?
- 11. 如何使用Python 2.4解壓文件?
- 12. 在python中解壓縮文件
- 13. 在java和python中解析非常大的bz2 xml文件(逐個元素)
- 14. 如何解壓/解壓縮* .z文件
- 15. 如何解壓/解壓縮文件
- 16. 在python中處理非常大的netCDF文件
- 17. 如何解析非常大的圖像?
- 18. 解壓縮Windows手機中的大文件導致OutOfMemory異常
- 19. PHP解壓縮大文件
- 20. 非常大的CSV文件
- 21. 在Windows上解析一個非常大的文本文件
- 22. 如何在Jelatics中解壓文件夾?
- 23. 在python中壓縮和解壓縮文本文件
- 24. 使用Imagemagick壓縮非常大的分辨率圖像文件
- 25. 如何在Python中壓扁XML文件
- 26. 如何在python中壓縮文件
- 27. 如何在Node.js中讀取非常大(> 1GB)的tar.gz文件?
- 28. 如何在C#中讀取非常龐大的文件?
- 29. 如何在HTML5中渲染非常大的SVG文件?
- 30. 如何使用子進程在python中解壓gz文件
這正是我所尋找的 - 謝謝! – 2008-12-04 03:55:34