Skip to content

Instantly share code, notes, and snippets.

@hzno
Created November 25, 2010 01:01
Show Gist options
  • Save hzno/714737 to your computer and use it in GitHub Desktop.
Save hzno/714737 to your computer and use it in GitHub Desktop.
(pycompress.py) A file is compressed by "tar.bz2", "tar.gz" or "zip".
#!/usr/bin/env python
# Author: Iyori Komiyama
# Contact: hazimarino@gmail.co.jp
# site: http://hazimarino.blogspot.com/
"""\
A file is compressed by "tar.bz2", "tar.gz" or "zip".
"""
import os
import tarfile
import zipfile
from fnmatch import fnmatch
exts = ['*.lzh', '*.zip', '*.rar', '*.gz', '*.bz2', '*.xz', '*.?[gbx]z']
def pycompress(cmpfile, types="bz2", min_size=16):
if os.stat(cmpfile).st_size > min_size:
if not any(fnmatch(cmpfile.lower(), p) for p in exts):
if types == "zip":
zp = zipfile.ZipFile("{0}.zip".format(cmpfile),
'w', zipfile.ZIP_DEFLATED)
zp.write(cmpfile)
zp.close()
else:
tar = tarfile.open('{0}.tar.{1}'.format(cmpfile, types),
'w:{0}'.format(types))
tar.add(cmpfile)
tar.close()
else:
print("It is already a data compressed file.")
else:
print("The file is too small. ")
if __name__ == '__main__':
import sys
try:
if sys.argv[2] == "bz2":
pycompress(sys.argv[1], 'bz2')
elif sys.argv[2] == "gz":
pycompress(sys.argv[1], 'gz')
elif sys.argv[2] == "zip":
pycompress(sys.argv[1], 'zip')
else:
raise
except (IndexError, TypeError):
print("Please input appropriate type (bz2, gz, zip). ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment