1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import os, os.path, stat, sys, string, glob, gzip
21
22 from pysys.constants import *
23 from pysys.exceptions import *
24
25
27 """Unzip all .gz files in a given directory.
28
29 @param path: The full path to the directory containing the archive files
30 @param binary: Boolean flag to indicate if the unzipped files should be written as binary
31 @raises FileNotFoundException: Raised if the directory path does not exist
32
33 """
34 if not os.path.exists(path):
35 raise FileNotFoundException, "%s path does not exist" % (os.path.basename(path))
36
37 for file in glob.glob('%s/*.gz'%(path)):
38 unzip(file, 1, binary)
39
40
41
42 -def unzip(zfilename, replace=False, binary=False):
43 """Unzip a .gz archive and write the contents to disk.
44
45 The method will unpack a file of the form C{file.data.gz} to C{file.data}, removing the
46 archive file in the process if the replace input parameter is set to true. By default the
47 unpacked archive is written as text data, unless the binary input parameter is set to true,
48 in which case the unpacked file is written as binary.
49
50 @param zfilename: The full path to the archive file
51 @param replace: Boolean flag to indicate if the archive file should be removed after unpacking
52 @param binary: Boolean flag to indicate if the unzipped file should be written as binary
53 @raises FileNotFoundException: Raised if the archive file does not exist
54 @raises IncorrectFileTypeEception: Raised if the archive file does not have a .gz extension
55
56 """
57 if not os.path.exists(zfilename):
58 raise FileNotFoundException, "unable to find file %s" % (os.path.basename(zfilename))
59
60 tokens = string.split(zfilename, '.')
61 if tokens[len(tokens)-1] != 'gz':
62 raise IncorrectFileTypeException, "file does not have a .gz extension"
63
64 uzfilename = ''
65 for i in range(len(tokens)-1):
66 uzfilename = uzfilename + tokens[i]
67 if i != len(tokens)-2:
68 uzfilename = uzfilename + '.'
69
70 zfile = gzip.GzipFile(zfilename, 'rb', 9)
71 if binary:
72 uzfile = open(uzfilename, 'wb')
73 else:
74 uzfile = open(uzfilename, 'w')
75 buffer = zfile.read()
76 uzfile.write(buffer)
77 zfile.close()
78 uzfile.close()
79
80 if replace:
81 try:
82 os.remove(zfilename)
83 except OSError:
84 pass
85
86
87
88 if __name__ == "__main__":
89 if len(sys.argv) < 2:
90 print "Usage: fileunzip <unzip> <file> or"
91 print " <unzipall> <path>"
92 sys.exit()
93 else:
94 try:
95 if sys.argv[1] == 'unzip':
96 status = unzip(sys.argv[2], 1)
97 elif sys.argv[1] == 'unzipall':
98 status = unzipall(sys.argv[2])
99 except:
100 print "caught %s: %s" % (sys.exc_info()[0], sys.exc_info()[1])
101 print "unable to perform unzip operation"
102