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
| import gzip import os import tarfile import zipfile import rarfile
def get_filetype(filepath): extension = filepath.split('.')[-2:] if extension[0] == 'tar' and extension[1] == 'gz': return 'tgz' return extension[1]
def uncompress(compress_file, dest_dir): extension = get_filetype(compress_file)
try: if not os.path.exists(dest_dir): os.mkdir(dest_dir) except Exception as a: return (False, 'Create Uncompressed Dir Failed', extension)
if extension in ('tgz', 'tar'): try: tar = tarfile.open(compress_file) names = tar.getnames() for name in names: tar.extract(name, dest_dir) tar.close() except Exception as e: return (False, e, extension)
elif extension == 'zip':
try: extension = zipfile.ZipFile(compress_file) for name in extension.namelist(): extension.extract(name, dest_dir) extension.close() except Exception as e: return (False, e, extension)
elif extension == 'rar':
try: rar = rarfile.RarFile(compress_file) os.chdir(dest_dir) rar.extractall() rar.close() except Exception as e: return (False, e, extension)
elif extension == 'gz': try: file_name = dest_dir + '/' + \ os.path.splitext(os.path.basename(compress_file))[0]
with gzip.open(compress_file, 'rb') as gz, open(file_name, 'wb') as f: f.write(gz.read())
except Exception as e: return (False, e, extension) else: return (False, 'Unsupported Compressed File Type', extension)
return (True, '', extension)
uncompress('git.txt.gz', 'gz')
|