bz2 module

Alex Martelli aleaxit at
Mon Oct 18 22:40:07 CEST 2004

Brad Tilley <bradtilley at> wrote:

> I'm having a bit of trouble using the bz2 module. The documentation for
> it is very poor. Here's what I'm trying to do:
> import bz2
> x = file('test.bkf', 'rb')
> while True:
>          data =
>          if not data:
>                  break
>          bz2.BZ2File('test.bkf.copy', 'w').write(data)
> x.close()
> It fails with this error:
> AttributeError: 'module' object has no attribute 'BZ2File'

Looks like your Python is misinstalled, or something...:

>>> import bz2
>>> bz2.BZ2File
<type 'bz2.BZ2File'>

> Can anyone give me an example of how to use bz2 to compress files. Why

import bz2
source = open('test.bkf', 'rb')
destination = bz2.BZ2File('test.bkf.bz2', 'w')

while True:
    data =
    if not data: break


> don't the docs give examples of this?!?

If the docs were perfect, who'd ever buy Python in a Nutshell, or the
Python Cookbook?  So I sneak in at night in the CVS repository and
secretly sabotage them just enough, destroying, without leaving a trace,
all the wonderful doc patches that people are submitting all the time,
fixing problems rather than whining about them...


More information about the Python-list mailing list