-
Notifications
You must be signed in to change notification settings - Fork 13
/
zip.py
99 lines (72 loc) · 2.69 KB
/
zip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
"""
An interface to the OOXML Document as a Zip file,
and a lightweight wrapper around Zipfile.
"""
__author__ = 'Brandon Gordon'
__email__ = '[email protected]'
import zipfile
class Zip(object):
"""
An interface to the OOXML Document as a Zip file,
and a lightweight wrapper around the `ZipFile` module.
:ivar pseudofile: Pseudofile of the Zip (OOXML) file.
:ivar filename: The filename of the Zip (OOXML) file.
:ivar zippartsinfo: A list containing a `ZipInfo` object for each
member of the Zip file. The `ZipInfo` object contains all
information about the member of the Zip file.
:ivar comment: The comment text associated with the Zip file.
"""
def __init__(self, pseudofile, filename):
"""
Initialize zip attributes.
:param pseudofile: Pseudofile of the document
:type pseudofile: os.BytesIO
:param filename: filename of the document
:type filename: string
"""
self.pseudofile = pseudofile
self.filename = filename
self._zipobj = zipfile.ZipFile(self.pseudofile, 'r')
self.zippartsinfo = self._zipobj.infolist()
self.comment = self._zipobj.comment
def testzip(self):
"""
Test zip CRC value.
:raises ZipCRCError: If the Zip CRC is incorrect
"""
if self._zipobj.testzip():
raise ZipCRCError("Zip file CRC is invalid")
def namelist(self):
"""
Get list of files in Zip archive.
:return: list of names of files in the Zip archive
"""
return self._zipobj.namelist()
def part_extract(self, partname):
"""
Extract part from the Zip archive.
:param partname: name of the :class:`~officedissector.part.Part` (member of the Zip archive)
to extract
:type partname: string
:return: file-like object of the member of the Zip archive.
"""
return self._zipobj.open(partname.lstrip('/'))
def part_info(self, partname):
"""
Get `ZipInfo` object for :class:`~officedissector.part.Part`.
:param partname: name of :class:`~officedissector.part.Part` (member of the Zip archive)
:type partname: string
:return: `ZipInfo`
"""
# Members of Zip archive do not have leading '/'
return self._zipobj.getinfo(partname.lstrip('/'))
def __repr__(self):
return "Zip File: %s" % self.filename
class ZipCRCError(Exception):
"""Raise an Exception when Zip CRC value is invalid."""
def __init__(self, msg):
Exception.__init__(self, msg)
self.msg = msg
def __str__(self):
return repr(self.msg)