How to compress a folder with everything inside using zipfile in python?

1

I'm trying to compress a file and a folder that has multiple files inside it into a single .zip file using Python. The script is as follows:

from zipfile import ZipFile,ZIP_DEFLATED

def zipar(lista):
    with ZipFile('teste.zip','w',ZIP_DEFLATED) as z:
        for i in lista:
            z.write(i)

zipar(['registro.py','Tudo'])

When you run the script, it compacts "registry.py" and the "All" folder, but the files that are inside the original "All" folder are not packed together, ie the folder is compressed empty. How do I fix this?

    
asked by anonymous 26.01.2017 / 21:59

2 answers

1

The problem is that you need to recursively specify directories within the Tudo directory and others you might want, you can do this via os.walk() ", and because registro.py is not in the same directory ( Tudo ) implies that you have to use zipfile :

import zipfile as zipf
import os

def zipar(arqs):
    with zipf.ZipFile('teste.zip','w', zipf.ZIP_DEFLATED) as z:
        for arq in arqs:
            if(os.path.isfile(arq)): # se for ficheiro
                z.write(arq)
            else: # se for diretorio
                for root, dirs, files in os.walk(arq):
                    for f in files:
                        z.write(os.path.join(root, f))

zipar(['registro.py','Tudo'])
    
27.01.2017 / 11:10
2

Use the shutil module that is much more practical.

Example:

...
├─── minha_pasta/
│    ├── tudo/
│    │   ├── sub_pasta_1/
│    │   │   ├── arquivo_1
│    │   │   └── arquivo_2
│    │   ├── sub_pasta_2/
│    │   │   ├── arquivo_3
│    │   │   └── arquivo_4
│    │   └── sub_pasta_3/
│    │       ├── arquivo_5
│    │       └── arquivo_6
│    └── registro.py
└─── script.py

script.py :

#!/usr/bin/env python
from shutil import make_archive

make_archive('pasta_compactada', 'zip', 'minha_pasta')

Result :

pasta_compactada.zip/
├── tudo/
│   ├── sub_pasta_1/
│   │   ├── arquivo_1
│   │   └── arquivo_2
│   ├── sub_pasta_2/
│   │   ├── arquivo_3
│   │   └── arquivo_4
│   └── sub_pasta_3/
│       ├── arquivo_5
│       └── arquivo_6
└── registro.py

For function details check documentation

If your directory structure is not the way you want, just adjust it with commands like shutil.copy2 .

    
27.01.2017 / 13:18