Skip to content

Conversation

@domragusa
Copy link
Contributor

@domragusa domragusa commented May 8, 2020

ZipFile.writestr doesn't work when a pathlike filename is used, the other methods do.

Example:

>>> a = ZipFile(Path('test.zip'), 'w') # this works
>>> a.write(Path('./foo.jpeg'), arcname=PurePath('/some/thing.jpeg')) # this works
>>> a.writestr(PurePath('/test.txt'), 'idk') # this doesn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/zipfile.py", line 1788, in writestr
    zinfo = ZipInfo(filename=zinfo_or_arcname,
  File "/usr/lib/python3.8/zipfile.py", line 349, in __init__
    null_byte = filename.find(chr(0))
AttributeError: 'PurePosixPath' object has no attribute 'find'

https://bugs.python.org/issue40506

Copy link

@remilapeyre remilapeyre left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @domragusa, this patch looks good.

FYI this is not the only method that causes issues with Path:

>>> import zipfile, pathlib
>>> 
>>> with zipfile.ZipFile('test.zip') as z:
...     print(z.open(pathlib.PurePath('example.nomad')))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/Users/remi/src/cpython/Lib/zipfile.py", line 1503, in open
    zinfo = self.getinfo(name)
  File "/Users/remi/src/cpython/Lib/zipfile.py", line 1430, in getinfo
    raise KeyError(
KeyError: "There is no item named PurePosixPath('example.nomad') in the archive"
>>> 
>>> with zipfile.ZipFile('test.zip') as z:
...     print(z.open('example.nomad'))
... 
<zipfile.ZipExtFile name='example.nomad' mode='r' compress_type=deflate>

Since the bpo issue only covers the writestr() method I think it would be best to report the issues with the rest of the method separately and fix them in another PR.

@gpshead
Copy link
Member

gpshead commented Dec 21, 2023

Thanks! I'm taking this work over in #113386, you are credited in the news entry.

@gpshead gpshead closed this Dec 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants