Extracting file from zip archive in Python 2.6.1

Brandon Taylor btaylordesign at gmail.com
Tue Feb 3 21:36:40 EST 2009


On Feb 3, 1:16 pm, Brandon Taylor <btaylordes... at gmail.com> wrote:
> On Feb 3, 9:45 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
>
>
>
> > En Tue, 03 Feb 2009 05:31:24 -0200, Brandon Taylor  
> > <btaylordes... at gmail.com> escribió:
>
> > > I'm having an issue specifying the path for extracting files from
> > > a .zip archive. In my method, I have:
>
> > > zip_file.extract(zip_name + '/' + thumbnail_image, thumbnail_path)
>
> > > What is happening is that the extract method is creating a folder with
> > > the name of 'zip_name' and extracting the files to it. Example:
>
> > extract will create all directories in member name. Use open instead:
>
> > with zip_file.open(zip_name + '/' + thumbnail_image) as source:
> >    with open(os.path.join(thumbnail_path, thumbnail_image), "wb") as target:
> >      shutil.copyfileobj(source, target)
>
> > (untested)
>
> > --
> > Gabriel Genellina
>
> Hi Gabriel,
>
> Thank you for the code sample. I figured I was going to have to use
> 'open', but I completely forgot about the 'with' statement. I was
> trying to figure out how to get access to the file object in the zip
> without having to loop over all of the items, and 'with' will allow me
> to do just that.
>
> I'll give it a shot when I get home this evening and post my results.
>
> Kind regards,
> Brandon

Ok, the first thing I needed to do was add:

from __future__ import with_statement at the beginning of my file

but:

with zip_file.open(zip_name + '/' + thumbnail_image) as source:
                    with open(os.path.join(thumbnail_path,
thumbnail_image), 'wb') as target:
                        shutil.copyfileobj(source, target)

Returns an error on the first line:

ZipExtFile instance has no attribute '__exit__'

Googling this error message is turning up nothing, and there's no
mention of the exception in the docs. Any thoughts?

TIA,
Brandon



More information about the Python-list mailing list