DEV Community

petercour
petercour

Posted on

1

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:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay