zipfile.
How It Works
zipfile.is_zipfile(filename_or_file) checks whether a path or file-like object contains recognizable ZIP structure. It does not verify every entry CRC, guarantee safety, or detect archive bombs.
Step-by-Step Example
import io
import zipfile
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, 'w') as archive:
archive.writestr('entry.txt', 'Ready')
print(zipfile.is_zipfile(io.BytesIO(archive_buffer.getvalue())))
print(zipfile.is_zipfile(io.BytesIO(b'not an archive')))
Understanding the Example
- The expression 'io.BytesIO()' supplies the value stored as 'archive_buffer'. This value is then used or checked by the later statements.
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
A successful run of this example prints the following output:
True
False
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Create a ZIP in memory and compare detection against ordinary bytes.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using is_zipfile() as a comprehensive security check or assuming it validates every compressed member.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- zipfile.
- zipfile.is_zipfile(filename_or_file) checks whether a path or file-like object contains recognizable ZIP structure.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.