forked from shubhabrataroy/MalwareDetection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7zip.py
More file actions
64 lines (54 loc) · 1.77 KB
/
7zip.py
File metadata and controls
64 lines (54 loc) · 1.77 KB
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
import os
import py7zlib
class SevenZFileError(py7zlib.ArchiveError):
pass
class SevenZFile(object):
@classmethod
def is_7zfile(cls, filepath):
""" Determine if filepath points to a valid 7z archive. """
is7z = False
fp = None
try:
fp = open(filepath, 'rb')
archive = py7zlib.Archive7z(fp)
n = len(archive.getnames())
is7z = True
finally:
if fp: fp.close()
return is7z
def __init__(self, filepath):
fp = open(filepath, 'rb')
self.filepath = filepath
self.archive = py7zlib.Archive7z(fp)
def __contains__(self, name):
return name in self.archive.getnames()
def bytestream(self, name):
""" Iterate stream of bytes from an archive member. """
if name not in self:
raise SevenZFileError('member %s not found in %s' %
(name, self.filepath))
else:
member = self.archive.getmember(name)
for byte in member.read():
if not byte: break
yield byte
def readlines(self, name):
""" Iterate lines from an archive member. """
linesep = os.linesep[-1]
line = ''
for ch in self.bytestream(name):
line += ch
if ch == linesep:
yield line
line = ''
if line: yield line
## Sample usage
import csv
if SevenZFile.is_7zfile('testing.csv.7z'):
sevenZfile = SevenZFile('testing.csv.7z')
if 'testing.csv' not in sevenZfile:
print 'testing.csv is not a member of testing.csv.7z'
else:
reader = csv.reader(sevenZfile.readlines('testing.csv'))
for row in reader:
print ', '.join(row)