问题
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?
回答1:
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
.
来源:https://stackoverflow.com/questions/28949548/create-symlink-inside-a-zipfile-in-memory-using-python