Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

unzip

temp

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__
like image 863
ericOnline Avatar asked Sep 02 '26 21:09

ericOnline


1 Answers

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

like image 114
Mantas Kandratavičius Avatar answered Sep 04 '26 13:09

Mantas Kandratavičius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!