Skip to content

ZipFile.mkdir() corrupts archives during an active write #156078

Closed

Description

@lpyu001

Bug description:

Summary

ZipFile.mkdir() does not reject calls made while another writable member handle returned by ZipFile.open(..., mode="w") is active. On seekable output,mkdir() seeks back to the current central-directory start and writes a new local header there. This overwrites or aliases the active member's local header and can produce a corrupt ZIP archive without raising an exception.

Minimal Reproducer

import io
import zipfile

buffer = io.BytesIO()
zf = zipfile.ZipFile(buffer, "w")

member = zf.open("file.txt", mode="w")
zf.mkdir("directory")       # Should reject this operation
member.write(b"payload")
member.close()
zf.close()

with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as broken:
    print(broken.namelist())
    print(broken.read("directory/"))

Observed behavior:

['directory/', 'file.txt']
Traceback (most recent call last):
  File "/home/ubuntu/cpython-main/test.py", line 15, in <module>
    print(broken.read("directory/"))
          ~~~~~~~~~~~^^^^^^^^^^^^^^
  File "/home/ubuntu/cpython-main/Lib/zipfile/__init__.py", line 2165, in read
    with self.open(name, "r", pwd) as fp:
         ~~~~~~~~~^^^^^^^^^^^^^^^^
  File "/home/ubuntu/cpython-main/Lib/zipfile/__init__.py", line 2239, in open
    raise BadZipFile(
        'File name in directory %r and header %r differ.'
        % (zinfo.orig_filename, fname))
zipfile.BadZipFile: File name in directory 'directory/' and header b'file.txt' differ.

The exact error may vary with the archive contents, but the resulting archive is structurally inconsistent.

Expected Behavior

mkdir() should reject the operation before changing the archive, consistent with the existing behavior of open(..., mode="w"), write(), writestr(), and close() when a writable member handle is active. A ValueError with a message explaining that another write handle is open would be appropriate.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. changed the title [-]`ZipFile.mkdir()` Corrupts Archives During an Active Write[/-] [+]`ZipFile.mkdir()` corrupts archives during an active write[/+] on Aug 20, 2026
  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Aug 20, 2026
  3. added 3 commits that reference this issue on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions