A
A
Alex Xmel2022-03-08 02:06:13
Python
Alex Xmel, 2022-03-08 02:06:13

How to work with zip archive in memory in Python without using disk?

Once a minute I receive an http zip archive. I open it, there are 8 text files, I write them to disk and then I work with them.

I am using this code:

responce = requests.get(url)
if responce.status_code == 200:
    zf = zipfile.ZipFile(io.BytesIO(responce.content))
    zf.extractall(DIR_NAME)
    return True


Everything works fine, but something was thinking: Why do I unzip this zip and write the resulting files to disk? I do not need the files themselves, but only some information from them. Accordingly, how can I unzip this zip in memory so that I get all these 8 text files also immediately in memory and can work with them here in memory?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2022-03-08
@Desead

content = {name: zf.read(name) for name in zf.namelist()}

A
Alex Xmel, 2022-03-08
@Desead

Everything turned out to be easier than I thought. I did this: (actually the same as suggested above):

files = {}
responce = requests.get(url)

with zipfile.ZipFile(io.BytesIO(responce.content), 'r') as zf:
    file_name = zf.namelist()
    for i in file_name:
        files[i] = []
        with zf.open(i) as f:
            for j in f.readlines():
                files[i].append(j.rstrip().decode('cp1251'))

as a result, I got a dictionary with the full contents of each file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question