Skip to content

Instantly share code, notes, and snippets.

@rubik
Created January 5, 2011 16:06
Show Gist options
  • Save rubik/766505 to your computer and use it in GitHub Desktop.
Save rubik/766505 to your computer and use it in GitHub Desktop.
Python archives infos
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])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment