From the course: Python: Working with Files
Create ZIP archives with Python - Python Tutorial
From the course: Python: Working with Files
Create ZIP archives with Python
- [Instructor] Archives are an easy way to package several files together for data storage or data transfer. With Python, we can create many different types of archives, including zip files. Zip is a common archive format that supports lossless data compression. To create a zip archive, we can use the zip file module in Python. For the function we'll call it create zip and we'll pass in a list of files that we want to put in the archive. To create the zip file, we'll follow the same pattern as we've seen previously. Where we open up the file and then write to it. We'll use the zip file module with zip file.zip file, then the name of the archive we want to create. We'll just call it archive.zip. We're going to write to this archive. We're going to create it. And we'll refer to it as archive. For each file and our file list, we'll write it out to the archive. This will archive all of our files. Now it's important to note that this will copy the file to the archive. It will not delete the file outside of the archive. Let's call this function and test it out. We'll create a list of file names and then pass them to create zip. Let's execute the program. If we go to our desktop, we can see the archive.zip. This is what our Python script created. If we click on it, we've opened the archive and extracted the files. There they are. Since we already had a ping folder on our desktop, this one got named ping2. Similar to writing text files, the right mechanism will overwrite any zip file of the same name. If you want to append to a zip file instead of overwriting it, all you have to do is change the mode to A or append. So we'll copy this function, change the mode to append and rename it. Now we have a function for a does it files. The zip file module works great for archiving files. But if you need to archive nested directories, we'll need to use a different module. Specifically, the shutil module. As mentioned before the shutil module is great for working with collections of files. With shutil we can create an archive with nested directories. To create the archive we'll call make archive from the shutil library. The first argument will be the archives name. We'll just call it directory archive. It will be of type zip, and we'll want to archive that directory path. Let's test out this function. We'll give it our SVG directory. This directory has nested directories one, two, and three each with their own files. Let's execute our program and watch this be archived. In our desktop, we have a directory archive. Let's open it up. With Python, we have flexibility to create zip files in many different ways.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.