About This Article
This article was created using an automated generation workflow powered by generative AI. Based on official Python zipfile documentation, we have organized a method to check file names, sizes, and encryption flags without extracting ZIP archives.Verification Status: 📘 Created based on official specification references; actual execution of the posted code on physical hardware has not been verified.
You want to check the contents of a ZIP file received via email, but extracting an unknown file directly is risky. In such cases, you can usea method to read the table of contents (central directory) information without extraction.Using only the Python standard libraryzipfile, you can list the file names, original sizes, and compressed sizes.
| Item | Condition |
|---|---|
| Target | Beginners and business operators who want to safely inspect ZIP contents in advance |
| Environment | Python 3, copy of the target ZIP file |
| Additional Installation | Not required |
| File Modification | Reads the ZIP only. No extraction or overwriting performed |
| Limitations | The file list can be verified, but the safety and authenticity of the contents are not guaranteed. |
- First, let's output the list.
- Points to observe
- Why it can be determined without extraction
- Change one thing and test
- Troubleshooting upon failure
- Note: Listing verification and secure extraction are separate issues
- Diagram: How the ZIP "Table of Contents" is read
- Creating a practice ZIP with known contents
- Order of verification prior to extraction
- Separating "primary inspection" and "safe extraction" for professional use
- Summary
- Official Documentation
First, let's output the list.
Place a copy of the target for investigation in the working folder under the name sample.zip and save the following Python code as inspect_zip.py. Ensure that confidential file names are not sent to logs or external services.
from pathlib import Path
from zipfile import ZipFile, BadZipFile
archive = Path("sample.zip")
try:
with ZipFile(archive, "r") as zf:
for item in zf.infolist():
kind = "DIR" if item.is_dir() else "FILE"
encrypted = "yes" if item.flag_bits & 0x1 else "no"
print(
f"{kind}\t{item.file_size}\t"
f"{item.compress_size}\t{encrypted}\t{item.filename}"
)
except (BadZipFile, OSError) as error:
print(f"ZIPを読み取れません: {error}")
It is expected that the type, uncompressed byte size, compressed byte size, encryption flag, and file name will be displayed in order from the beginning.This output is an expected result derived from the specification and is not an execution log.
infolist() returned by ZipInfo contains the metadata for each entry.file_size is the uncompressed size, and compress_size is the compressed size. Directories can be determined by is_dir().
Points to observe
| Observation result | Possible meaning | Next action |
|---|---|---|
| Unexpected file name | Possibility that the sender's explanation differs from the contents | Confirm with the sender without extracting |
| Extremely large uncompressed size | Potential disk space consumption upon extraction | Check capacity and operational limits |
| Encryption flag is set to yes | Potential encrypted entry | Verify via authorized sharing channels |
| Unable to read ZIP | Corruption, format mismatch, permission issues, etc. | Verify original data and file format |
flag_bits & 0x1 only checks the encryption bit in the ZIP general purpose flags.It does not evaluate the encryption method or password strength. Furthermore, retrieving the file list does not constitute running a virus scan.
Why it can be determined without extraction
ZIP files contain a central directory that records entry names and sizes separately from the file contents.ZipFile reads this information andinfolist() returns the list. This code does not call extract() or extractall(). Therefore, it does not write files from the ZIP to the designated folder.
However, this does not mean that parsing ZIP files is entirely harmless. Handle untrusted input using an updated version of Python and, if possible, in an isolated environment.
Change one thing and test
If the list is long,for item in zf.infolist():There is a method to add the following condition immediately after .
if item.is_dir():
continue
This allows listing only the files, excluding directory entries. The expected behavior after modification is inferred from specifications and has not been execution-verified.
Troubleshooting upon failure
FileNotFoundErrorWhen is displayed: Check the ZIP file name and the runtime working folder. In this example, it is caught as .OSErroris caught as .BadZipFileIn the case of : The file may be corrupted or not in ZIP format. Do not determine that a file is a ZIP based on its extension alone.When file names are garbled: The character encoding specification or compatibility of the ZIP creation tool may be the cause. Do not edit the original ZIP; check with the creator.
When the list is empty: There may be no entries in the ZIP. Do not assume the presence of contents.
Note: Listing verification and secure extraction are separate issues
ZIP entry names may contain relative paths or suspicious names. Simply checking the names does not guarantee secure extraction. In particular, processing that constructs destination paths independently using file names requires countermeasures against path traversal. Also, beware of ZIPs with huge total extracted sizes or those containing a large number of entries.
This method ispre-extraction preliminary verification. It does not replace source verification, anti-malware measures, or inspection in an isolated environment as needed.
Diagram: How the ZIP "Table of Contents" is read
A ZIP is not just a collection of compressed file data. It has a table of contents called the "central directory" that organizes the name and size of each entry, and Python's ZipFile uses it to create a list. "Extraction," which actually writes files out, and "listing," which references the information recorded in the ZIP, are distinct operations.
flowchart LR
A["ZIPアーカイブ"] --> B["圧縮された各ファイル"]
A --> C["中央ディレクトリ(目次)"]
C --> D["ZipInfoで名前・容量・フラグを読む"]
D --> E["一覧を表示"]
E --> F["想定外のファイルを探す"]
B -.->|"一覧表示では展開しない"| E
This diagram is conceptual and does not strictly show the physical storage location inside the ZIP. Even if the names in the table of contents can be read, it does not guarantee that the entries can be extracted normally or executed safely. If the ZIP is received from an external source, treat the information in the table of contents carefully as external input.
Creating a practice ZIP with known contents
You do not need to use an unknown file as your initial learning material. By creating your own ZIP containing only a dummy CSV and a short description, you can safely compare each column of the list display with the actual contents. The following code is an example of newly creating a practice file. If a file with the same name already exists, it stops without overwriting. Since it has not been executed at the time of writing, the following is an assumed procedure rather than an actual measurement.
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile
output = Path("training-archive.zip")
if output.exists():
raise FileExistsError("同名ファイルがあるため中断します")
with ZipFile(output, "w", compression=ZIP_DEFLATED) as zf:
zf.writestr("report/summary.csv", "項目,値\nA,1\n")
zf.writestr("readme.txt", "これは架空の教材です")
print("練習用ZIPを作成しました:", output)
Specifying this ZIP in the first half listing code is expected to display report/summary.csv and readme.txt. Because folder entries do not always exist independently within a ZIP, apparent discrepancies such as "showing 2 files but folders are also visible" are not necessarily abnormal. Also, the number of characters and bytes do not match. Understanding will be enhanced if you are also aware of how many bytes result in UTF-8 when comparing the sizes of text containing Japanese.
Compression does not always result in a smaller size
While texts with many repetitions are easily compressed significantly, already compressed data such as JPEG images or videos may not become much smaller. In very short strings, the additional metadata required for compression can sometimes make the compressed size appear larger than the original. Therefore, if the display indicates that the compressed size is larger than the original size, this alone does not necessarily signify file corruption or an attack.
Now, what if the compressed size is extremely small compared to the original size? While files containing massive amounts of identical repeated data are possible, one must also be cautious of risks such as ZIP bombs, which consume enormous memory and processing time during extraction. However, neither a high compression rate alone can confirm malicious intent, nor can a low rate be deemed safe. Evaluation is performed by combining the file count, total original size, format, and receipt purpose.
Order of verification prior to extraction
flowchart TD
A["ZIPの一覧を取得"] --> B{"一覧が読めたか"}
B -->|"いいえ"| C["破損・形式・対応版を確認して保留"]
B -->|"はい"| D{"不審なパス・容量・件数があるか"}
D -->|"はい"| E["展開せず送付元と用途を確認"]
D -->|"いいえ"| F["暗号化・期待したファイル名を確認"]
F --> G{"内容を取り出す必要があるか"}
G -->|"ない"| H["一覧確認のみで終了"]
G -->|"ある"| I["別の安全な検査・展開工程へ"]
In this workflow, simply being able to read the file list does not certify safety. For example, if you expect to receive a single PDF for business purposes, but the archive contains dozens of executable files, this serves as grounds to contact the sender rather than extracting the archive. Conversely, even if only the names of expected PDFs are listed, it does not reveal the authenticity of their contents or the presence of malware.
Even if names within the ZIP contain symbols indicating parent directories or absolute path notations, viewing the list alone does not write files to those locations. However, custom extraction routines that bind those names directly to the save destination are dangerous. Path traversal countermeasures must be implemented separately during the extraction process. The presence of an encryption flag does not imply safety; the presence of encryption and the inspectability of content are distinct matters.
Consider privacy when sharing file lists
Even without extracting the main files, internal file names may include customer names, case numbers, or personal information. Pasting them directly into investigation logs or chat applications can lead to information leaks via the table of contents alone. Restrict the sharing scope, such as by displaying only necessary extensions and counts. If file names appear corrupted due to character encoding issues, do not immediately rewrite the names and resave the original ZIP; instead, verify the conditions regarding the originating tool and character encoding.
Separating "primary inspection" and "safe extraction" for professional use
Consider batch files received daily as an example. If specific CSV files are expected to be in the ZIP, the system can be designed to list file names, counts, and original sizes immediately upon receipt, routing items that deviate significantly from expectations to human review. This is not an inspection to confirm that the contents are correct, but an early-stage check to see whether the structure appears as expected.
At the stage where contents are actually processed, separate security measures such as antivirus scans, sender reliability checks, actual data validation, and destination permission controls are required. To avoid confusing successful list retrieval with usability as business data, explicitly defining the scope of judgment in procedure manuals makes it easier to apply practically. Distinguishing between "what can be investigated without opening" and "what can only be understood by opening" is an essential application of this small technique.
Summary
Rather than extracting a ZIP immediately,ZipFile.infolist() allows you to check the names and sizes of its contents. Compare the original and compressed sizes, and if there are unexpected files or extreme capacities, pause and verify before extraction. This is a minor procedure to increase decision-making data rather than a guarantee of safety.
Official Documentation
Verification Notes (November 5, 2026)Structure based on official documentation. Execution of published code, verification with actual ZIPs, and confirmation of WordPress display have not been performed.
