Mailing List Archive

Using the compression module
Hello,
I'm looking for a simple example of how to use the compression module, gzip.
All I want to do is a make a compressed copy of a file. From the gzip
documentation I see how to open a file for compression but I'm not sure what
to do with it after that. From the gzip documentation:

open (fileobj[, filename[, mode[, compresslevel]]])
Returns a new GzipFile object on top of fileobj, which can be a regular
file, a StringIO object, or any object which simulates a file.

Okay, so I opened this file object :

f=open('/Audit.dbf','r')
test=gzip.GzipFile('Auditc','r','9',f)

So now how do I produce a compressed version of it?

Thanks,
Ben
Using the compression module [ In reply to ]
Benjamin Derstine writes:
From the gzip documentation:
>open (fileobj[, filename[, mode[, compresslevel]]])
> Returns a new GzipFile object on top of fileobj, which can be a regular
>file, a StringIO object, or any object which simulates a file.

Are you sure that's what the documentation says? The current
documentation has filename, mode, compresslevel, fileobj, which
matches the code. Check the current documentation on
www.python.org/doc/lib/ .

>f=open('/Audit.dbf','r')
>test=gzip.GzipFile('Auditc','r','9',f)

The first line opens Audit.dbf for reading. However, if you
want to make a compressed version of it, the second line is wrong;
it's trying to make a compressed file object from the uncompressed
/Audit.dbf. Instead, you need to open a compressed file for writing:

f=open('/Audit.dbf','r')
test=gzip.GzipFile('Auditc', 'w')

test.write() will then write data to the compressed file, so you need
a loop to copy between the two files:

while 1:
chunk = f.read(4096) # Work in chunks of 4K
if chunk == "": break # End-of-file? Break out of the loop
test.write( chunk )
f.close()
test.close()

--
A.M. Kuchling http://starship.python.net/crew/amk/
I had known him for years in a casual way, but I had never seen very deeply
into him. He seemed to me to have more conscience than is good for any man. A
powerful conscience and no sense of humour -- a dangerous combination.
-- Robertson Davies, _The Rebel Angels_