DEV Community

petercour
petercour

Posted on

Zip with Python

zip

You can zip and extract zip files with Python. What? yes.. you can. There's a module named zipfile which lets you do that

To add a single file

#!/usr/bin/python3
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
f.write('file_to_add.py')
f.close()

Create a zip program

Now you can do this in a command line interface with the fire module

#!/usr/bin/python3
import fire
import zipfile

class ZipApp(object):

    def create_zip(self, filename, yourfile):
        f = zipfile.ZipFile(filename,'w',zipfile.ZIP_DEFLATED)
        f.write(yourfile)
        f.close()


    def unzip(self,filename):
        zfile = zipfile.ZipFile(filename,'r')
        for filename in zfile.namelist():
            data = zfile.read(filename)
            file = open(filename, 'w+b')
            file.write(data)
            file.close()

if __name__ == '__main__':
    fire.Fire(ZipApp)

Then just use the terminal to create your zips:

python3 zip.py create-zip example.zip zip.py
python3 zip.py unzip example.zip

Would you use this to replace unzip in Linux? probably not, but it's fun to create zip with code.

Depending on your program, it may be useful to store data into zip files or extract zip files.

Learn Python:

Top comments (0)