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

前端 未结 7 2116
甜味超标
甜味超标 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 07:06

    The earlier answers did not work for me (on OS X 10.12). I found that as well as the executable flags (octal 755), I also need to set the "regular file" flag (octal 100000). I found this mentioned here: https://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute

    A complete example:

    zipname = "test.zip"
    filename = "test-executable"
    
    zip = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
    
    f = open(filename, 'r')
    bytes = f.read()
    f.close()
    
    info = zipfile.ZipInfo(filename)
    info.date_time = time.localtime()
    info.external_attr = 0100755 << 16L
    
    zip.writestr(info, bytes, zipfile.ZIP_DEFLATED)
    
    zip.close()
    

    A complete example of my specific usecase, creating a zip of a .app so that everything in the folder Contents/MacOS/ is executable: https://gist.github.com/Draknek/3ce889860cea4f59838386a79cc11a85

提交回复
热议问题