How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?

前端 未结 7 2130
甜味超标
甜味超标 2020-11-30 06:20

When I extract files from a ZIP file created with the Python zipfile module, all the files are not writable, read only etc.

The file is being created and extracted u

7条回答
  •  心在旅途
    2020-11-30 06:55

    You can extend the ZipFile class to change the default file permission:

    from zipfile import ZipFile, ZipInfo
    import time
    
    class PermissiveZipFile(ZipFile):
        def writestr(self, zinfo_or_arcname, data, compress_type=None):
            if not isinstance(zinfo_or_arcname, ZipInfo):
                zinfo = ZipInfo(filename=zinfo_or_arcname,
                                date_time=time.localtime(time.time())[:6])
    
                zinfo.compress_type = self.compression
                if zinfo.filename[-1] == '/':
                    zinfo.external_attr = 0o40775 << 16   # drwxrwxr-x
                    zinfo.external_attr |= 0x10           # MS-DOS directory flag
                else:
                    zinfo.external_attr = 0o664 << 16     # ?rw-rw-r--
            else:
                zinfo = zinfo_or_arcname
    
            super(PermissiveZipFile, self).writestr(zinfo, data, compress_type)
    

    This example changes the default file permission to 664 and keeps 775 for directories.

    Related code:

    • ZipFile.writestr, Python 2.7
    • ZipFile.writestr, Python 3.6

提交回复
热议问题