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

Offen Anfängerfreundlich
#153,771 5 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
72/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Ruhig
Tech-Stack
python
Bereich
backend

Rechercherichtung

Beginne in zipfile/init.py bei ZipFile.writestr(), ZipInfo.init() und _sanitize_filename(), und führe anschließend die pathlib.Path-Reproduktion aus dem Issue aus. Erledigt ist die Aufgabe, wenn writestr() os.PathLike-Objekte wie pathlib.Path akzeptiert, ohne AttributeError auszulösen, und dabei das bestehende Verhalten für Strings beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

stdlib type-feature

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

Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
Ø Merge
1 T. 10 Std.
Gemergte PRs (30 T.)
560

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/cpython

Alle Issues in python/cpython

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.