This quick guide demonstrates how to remove file from ZIP in Python. It covers all the details, including the program flow and the sample code to delete ZIP file in Python. Moreover, you can follow this approach in any operating system where Python is configured.
Steps to Delete File From ZIP in Python
- Configure the environment by installing Aspose.ZIP in your system
- Initiate an instance of the Archive class and load the source archive
- Iterate through all the entries in the archive and filter the files containing a specific string
- Delete all the files matching the criteria using the delete_entry method
- Save the output ZIP archive
These steps outline the simple approach to delete file from ZIP in Python. It simply creates a list of all the files that contain a specific string in their file name. Subsequently, it deletes all such files and exports the output directory to the disk.
Code to Delete ZIP File in Python
import aspose.zip as az | |
from io import BytesIO | |
# Load the ZIP archive | |
with az.Archive("sample.zip") as archive: | |
# List to keep files to be deleted | |
entriesToDelete = [] | |
# Loop through ZIP entries | |
for entry in archive.entries: | |
# Add file/folder into list | |
if "data" in entry.name.lower(): | |
entriesToDelete.append(entry) | |
# Delete all listed entries | |
for entry in entriesToDelete: | |
archive.delete_entry(entry) | |
# Save output ZIP archive | |
archive.save("archive.zip") |
This code snippet demonstrates how to remove a ZIP file in Python. However, you may modify it further, like deleting the specific files by passing their position index. For instance, you can selectively delete the first, last, or any other file simply by specifying their index number in the archive.
This topic has covered how to delete zipped files in Python. Whereas, if you need to create a ZIP file, then take a look at the article on Create ZIP in Python.