简体   繁体   中英

Create symlink inside a zipfile in memory using python

I am looking for a way to create a zipfile in memory and include a symlink inside the zipfile. So far I have found this link and try the following code:

from zipfile import ZipInfo
from zipfile import ZipFile
from zipfile import ZIP_DEFLATED, ZIP_STORED
from cStringIO import StringIO
import codecs


buf = StringIO()
zipfile = ZipFile( buf,'w')

zipinfo = ZipInfo()
zipinfo.filename = u'bundle/'
zipinfo.compress_type = ZIP_STORED
zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x
zipinfo.external_attr |= 0x10 # MS-DOS directory flag
zipfile.writestr(zipinfo, '')


path = u'bundle/test.txt'
zipinfo = ZipInfo(path)
zipinfo.compress_type = ZIP_DEFLATED
zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r--
zipfile.writestr(zipinfo, u'Test content')

dest = path

#create symbolic link (success)
zipinfo = ZipInfo()
zipinfo.filename = u'test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)


#create symbolic link (failed)
zipinfo = ZipInfo()
zipinfo.filename = u'bundle1/test_link.txt'
zipinfo.external_attr |= 0120000 << 16L # symlink file type
zipinfo.compress_type = ZIP_STORED
zipfile.writestr(zipinfo, dest)

for info in zipfile.infolist():
    print u'filename %s' %info.filename
    print u'external_attr %s' %info.external_attr
    print u'header_offset %s' %info.header_offset
    print u'file_size %s' %info.file_size
    print u'crc %s' %info.CRC 
    print u'\n\n'


zipfile.close()
buf.reset()
with codecs.open('test.zip', 'w') as f:
    f.write(buf.getvalue())
buf.close()

The code above was able to create symlink successfully if the link is located directly under the root of unzip folder otherwise it is failed (after unzip if I try to open the symlink file bundle1/text1.txt, and it return an warning

The operation can't be completed because the original item for “test_link.txt” can't be found.

Could you please help me how to get symlink bundle1/test_link.txt works properly?

If you create a symlink in bundle1 that points to bundle/test.txt , the target would have to be located in bundle1/bundle/test.txt . Symlinks alre always relative to their own path (unless of course they start with a / )

So to make this work, you need to change the link destination to ../bundle/test.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM