public
Created

Python archives infos

  • Download Gist
infos.py
Python
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
import os
import time
import tarfile
import zipfile
 
def bytes2str(bytes):
if bytes < 0: return "0 B"
if bytes < 1024: return "%.2f B" % (bytes)
elif bytes < 1048576: return "%.2f Kb" % (bytes / 1024)
elif bytes < 1073741824: return "%.2f Mb" % (bytes / 1048576)
elif bytes < 1099511627776: return "%.2f GB" % (bytes / 1073741824)
else: return "%.2f Tb" % (bytes / 1099511627776)
 
def infos(path):
name, ext = os.path.splitext(os.path.basename(path))
if ext in ('.gz', '.bz2'):
if name.endswith('.tar'):
return tar(path, ext[1:])
return gz_bz2_infos(path)
elif ext == '.tar':
return tar(path)
return zip(path)
 
def gz_bz2_infos(path):
s = os.stat(path)
yield bytes2str(s.st_size), time.gmtime(s.st_mtime)
 
def tar(path, type=''):
t = tarfile.open(path, 'r:' + type)
for tinfo in t:
if tinfo.isdir():
continue
yield tinfo.name, bytes2str(tinfo.size), time.gmtime(tinfo.mtime)
t.close()
 
def zip(path):
with zipfile.ZipFile(path) as z:
for zinfo in z.infolist():
yield zinfo.filename, bytes2str(zinfo.file_size), tuple(list(zinfo.date_time) + [0, 0, 0])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.