Extracting Member Files and Closing ZIP Files
00:00 Extracting Member Files and Closing ZIP Files. Extracting the content of a given archive is one of the most common operations that you’ll do on ZIP files. Depending on your needs, you may want to extract a single file at a time or all the files in one go.
If the target filename already exists in the output directory, then
.extract() overwrites it without asking for confirmation. If the output directory doesn’t exist, then
.extract() creates it for you.
When it comes to extracting all the member files from an archive, you can use
.extractall(). As its name implies, this method extracts all the member files to a destination path, which is the current directory by default.
If you pass a non-existing directory to
.extractall(), then this method automatically creates the directory. Finally, if any of the member files already exist at the destination directory, then
.extractall() will override them without asking for confirmation, so be careful when using this method.
If you only need to extract some of the member files from a given archive, then you can use the
members argument. This argument accepts a list of member files, which should be a subset of the whole list of files in the archive at hand.
.extractall() method also accepts a
pwd argument to extract encrypted files. Sometimes it’s convenient for you to open a given ZIP file without using a
with statement. In those cases, you need to manually close the archive after use to complete any writing operations and to free the acquired resources.
You must call
.close() before exiting your program. Otherwise, some writing operations may not be executed. For example, if you open a ZIP file for appending (
"a") new member files, then you need to close the archive to write the files.
The call to
.close() closes the archive for you. In the next section of the course, you’ll look further into the creation of ZIP files, starting with the creation of compressed files and directories.
Become a Member to join the conversation.