كيف قمت بفك الملفات الكبيرة جدا في بيثون؟
-
19-08-2019 - |
سؤال
وعن طريق بيثون 2.4 و المكتبة ZipFile
المدمج في، وأنا لا يمكن قراءة الملفات المضغوطة كبيرة جدا (أكثر من 1 أو 2 GB) لأنها تريد لتخزين محتويات ملف مضغوط في الذاكرة. هل هناك طريقة أخرى للقيام بذلك (إما مع مكتبة طرف ثالث أو بعض الدول الأخرى الإختراق)، أو يجب أن "قذيفة من أصل" وبفك الأمر على هذا النحو (والذي هو ليس كما عبر منصة، من الواضح).
المحلول
وفيما يلي عرض موجز لإزالة الضغط من الملفات الكبيرة.
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()
نصائح أخرى
واعتبارا من بيثون 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، نسخها أكثر من ملف الإخراج.
لا تنتمي إلى StackOverflow