Unzip to temp (in-memory) directory using Python mkdtemp()?
Asked Answered
J

1

6

I've looked through the examples out there and don't seem to find one that fits.

Looking to unzip a file in-memory to a temporary directory using Python mkdtemp().

Something like this feels intuitive, but I can't find the correct syntax:

import zipfile
import tempfile


zf = zipfile.Zipfile('incoming.zip')

with tempfile.mkdtemp() as tempdir:
    zf.extractall(tempdir)

# do stuff on extracted files

But this results in:

AttributeError                            Traceback (most recent call last)
<ipython-input-5-af39c866a2ba> in <module>
      1 zip_file = zipfile.ZipFile('incoming.zip')
      2 
----> 3 with tempfile.mkdtemp() as tempdir:
      4     zip_file.extractall(tempdir)

AttributeError: __enter__
Joaniejoann answered 5/1, 2021 at 1:4 Comment(3)
You can't use .mkdtemp() with with and as. It returns the path name as a string and not a context manager. Read this -> Python: Why am I receiving an AttributeError: __enter__Incautious
mkdtemp() does not return a context manager. It returns a path. You have to handle it manually. And it also does not work in-memory except your temp directory is on a RAM drive.Evocation
You're looking for tempfile.TemporaryDirectory I reckon as it comes with context manager. But really depending on what you are trying to do, there is a good chance you do not need to unpack the zip first in order to do that.Kitchenware
P
12

I already mentioned in my comment why the code that you wrote doesn't work. .mkdtemp() returns just a path as a string, but what you really want to have is a context manager.

You can easily fix that by using the the correct function .TemporaryDirectory()

This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.


zf = zipfile.ZipFile('incoming.zip')

with tempfile.TemporaryDirectory() as tempdir:
    zf.extractall(tempdir)

This alone would work

Paranoiac answered 5/1, 2021 at 1:19 Comment(1)
I was close! Thank you for getting me past that. I now have more understanding (and homework to do).Joaniejoann

© 2022 - 2024 — McMap. All rights reserved.