Does Python zipfile always use posixpath filenames regardless of operating system?

538 views Asked by At

It probably won't matter for my current utility, but just for good coding practice, I'd like to know if files in a ZIP file, using the zipfile module, can be accessed using a POSIX-style pathname such as subdir/file.ext regardless of on which operating system it was made, or on what system my Python script is running. Or if, in the case of Windows, the file will be stored or accessed as subdir\file.ext. I read the pydoc for the module, and did some searches here and on Google, but couldn't see anything relevant to this question.

2

There are 2 answers

0
Wang Dingwei On BEST ANSWER

Yes.

You can see these lines from the zipfile module:

# 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, "/")

And in the Zip specification:

file name: (Variable)

The name of the file, with optional relative path. The path stored should not contain a drive or device letter, or a leading slash. All slashes should be forward slashes '/' as opposed to backwards slashes '\' for compatibility with Amiga and UNIX file systems etc.

0
user18236245 On

I have the same problem in the zipfile.py module. os.path.sep returns {AttributeError}module 'posixpath' has no attribute 'sep' so I modified the file in

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

by replacing os.path.sep by os.sep (which returns the correct value / on a mac operating system).

It solves the problem both for zipfile open and extract methods.