zip文件创建与python2工作正常当我为python 3运行相同的代码时创建的zip文件不是一个合适的zip(即当我解压缩storage_aligned.zip时)它会抛出错误
Archive: storage_aligned.zip
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of storage_aligned.zip or
storage_aligned.zip.zip, and cannot find storage_aligned.zip.ZIP, period
代码段:
aligned_zf = zipfile.ZipFile(file, 'w')
for zinfo in self.filelist:
zef_file = self.fp
zef_file.seek(zinfo.header_offset, 0)
fheader = zef_file.read(zipfile.sizeFileHeader)
if fheader[0:4] != zipfile.stringFileHeader:
raise BadZipfile("Bad magic number for file header")
fheader = struct.unpack(zipfile.structFileHeader, fheader)
fname = zef_file.read(fheader[zipfile._FH_FILENAME_LENGTH])
if fheader[zipfile._FH_EXTRA_FIELD_LENGTH]:
zef_file.read(fheader[zipfile._FH_EXTRA_FIELD_LENGTH])
if fname.decode('utf-8') != zinfo.orig_filename:
raise zipfile.BadZipfile('File name in directory "%s" and header "%s" differ.' % (
zinfo.orig_filename, fname))
# For the first entry, prepend some extraneous bytes before the LFH. This
# is acceptable since ZIP implementations use the CD (end of the file) to
# find entries. Therefore these bytes are ignored
if padding_index == 0:
if sys.version[:1] == '2':
aligned_zf.fp.write(bytes("\0"*paddings[padding_index]))
elif sys.version[:1] == '3':
aligned_zf.fp.write(bytes("\0"*paddings[padding_index], 'utf-8') )
padding_index += 1
# if required, add padding after the file data. This is acceptable as the CD
# references offsets to the LFHs. Therefore extraneous data is ignored and not processed
# orig: aligned_zf.writestr(zinfo, self.read(fname)+'\0'*paddings[padding_index])
aligned_zf.writestr(zinfo, self.read(fname.decode('utf-8')))
if sys.version[:1] == '2':
aligned_zf.fp.write('\0'*paddings[padding_index])
elif sys.version[:1] == '3':
aligned_zf.fp.write(bytes('\0'*paddings[padding_index], 'utf-8'))
padding_index+=1
aligned_zf.close()