python / python/cpython

`zipfile.ZipFile.writestr()` raises `AttributeError` instead of accepting `os.PathLike` objects (e.g. `pathlib.Path`)

未关闭 适合新手
#153,771 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

Unlike ZipFile.write() (which accepts os.PathLike objects such as pathlib.Path for both its filename and arcname arguments), ZipFile.writestr() fails when passed a PathLike object as its zinfo_or_arcname parameter.

Instead of converting it to a string using os.fspath() (as expected by modern standard library conventions), it attempts to call .find(chr(0)) directly on the path object, resulting in an immediate AttributeError.

Repro:

import zipfile
import pathlib
import io
z = zipfile.ZipFile(io.BytesIO(), 'w')
# Passes a pathlib.Path instead of a raw string
z.writestr(pathlib.Path('foo.txt'), b'hello')

Traceback:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../zipfile/__init__.py", line 2020, in writestr
    zinfo = ZipInfo(zinfo_or_arcname)._for_archive(self)
            ^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../zipfile/__init__.py", line 455, in __init__
    filename = _sanitize_filename(filename)
  File ".../zipfile/__init__.py", line 410, in _sanitize_filename
    null_byte = filename.find(chr(0))
                ^^^^^^^^^^^^^
AttributeError: 'PosixPath' object has no attribute 'find'
CPython versions tested on:

3.14

Operating systems tested on:

macOS

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 zipfile/init.py 中的 ZipFile.writestr()、ZipInfo.init() 和 _sanitize_filename() 开始,然后运行 issue 中使用 pathlib.Path 的复现步骤。完成的标准是 writestr() 接受诸如 pathlib.Path 之类的 os.PathLike 对象而不引发 AttributeError,同时保留现有的字符串行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
冷清
描述清晰度
描述清楚
新手友好度
72/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。