Search code examples
pythonzipunzip

Get path from open zip file in Python


So the code I'm working with unstores a sample file from a zip like that:

with ZipFile('spam.zip') as myzip:
    myfile = myzip.open('eggs.txt')

return myfile  # <class 'zipfile.ZipExtFile(io.BufferedIOBase)'>

I need to work with FileResponse which expects a path to a file. So when checking how to retrieve the path of an opened file in Python the solutions seems to be (according to Get path from open file in Python):

myfile.name

But unfortunately this doesn't work with ZipExtFile. It just returns the files' name instead of a path to where this unpacked file is stored.

How can I get the path from myfile?
Or is there another way to get the file and it's path without changing the original zip file?


Solution

  • The issue here is that instead of opening the zip file and extracting a file as you would do in a GUI, what you're doing there is actually opening and reading the content of the file into the io.BufferedIOBase class format.

    If you plan to use one of the files inside the zip file, you need to either extract it, or create a new file from the content you read into your variable. I would prefer the first option:

    myzip = zipfile.ZipFile('spam.zip')
    path_to_extracted_file = myzip.extract('eggs.txt')
    

    Then you can pass path_to_extracted_file to FileResponse. This will keep your original zip file intact.