Python的zipfile在任何操作系统中是否总是使用posixpath文件名?

1 投票
2 回答
536 浏览
提问于 2025-04-16 12:03

对于我现在的工具来说,这个问题可能不太重要,但为了养成良好的编码习惯,我想知道使用zipfile模块时,ZIP文件里的文件能否用类似于POSIX风格的路径名来访问,比如subdir/file.ext,不管这个ZIP文件是在哪个操作系统上创建的,或者我的Python脚本在哪个系统上运行。还有,像在Windows系统上,这个文件是会以subdir\file.ext的形式存储或访问吗?我查阅了这个模块的文档,也在这里和谷歌上做了一些搜索,但没有找到相关的信息。

2 个回答

0

我在zipfile.py这个模块里也遇到了同样的问题。os.path.sep 返回了 {AttributeError}module 'posixpath' has no attribute 'sep',所以我修改了这个文件。

def _extract_member(self, member, targetpath, pwd):
"""Extract the ZipInfo object 'member' to a physical
file on the path targetpath.
"""

我把 os.path.sep 替换成了 os.sep(在mac操作系统上,这个返回的值是正确的 /)。

这样做解决了zipfile的打开和提取方法的问题。

3

是的。

你可以在zipfile模块中看到这些代码:

# This is used to ensure paths in generated ZIP files always use
# forward slashes as the directory separator, as required by the
# ZIP format specification.
if os.sep != "/" and os.sep in filename:
    filename = filename.replace(os.sep, "/")

还有在Zip规范中:

文件名:(可变)

文件的名称,可以有相对路径。存储的路径不应该包含驱动器或设备字母,也不要有开头的斜杠。所有的斜杠应该使用正斜杠 '/',而不是反斜杠 '\',这样可以和Amiga及UNIX文件系统等保持兼容。

撰写回答