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
分支
36k
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 摘要。