Search code examples
pythonunziptemp

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


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__

Solution

  • 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