Last active
December 4, 2015 06:43
-
-
Save GaryLee/61c460cc7018096d32f8 to your computer and use it in GitHub Desktop.
Zip/unzip files under specified folders.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!python | |
| # coding: utf-8 | |
| """Zip/unzip files under specified folders.""" | |
| import sys | |
| from os import walk, path, remove | |
| import zipfile | |
| class App(object): | |
| """Convert files under specified folder to zip file. Or, turn it back.""" | |
| excluded_exts = map(lambda x: x.lower(), | |
| ['.png', '.jpg', '.jpeg', '.mp3', '.mp4', '.zip', '.gz', '.tgz', | |
| '.rar', '.7z']) | |
| def __init__(self, argv=[]): | |
| self.parse_arg(argv) | |
| def parse_arg(self, argv): | |
| '''Handle command line arguments.''' | |
| import argparse | |
| parser = argparse.ArgumentParser(description=self.__doc__) | |
| parser.add_argument('subcmd', choices=['zip', 'unzip'], help='zip or unzip files.') | |
| parser.add_argument('folder', nargs='+', help='The folders to be processed.') | |
| self.args = parser.parse_args(argv) | |
| def get_fileext(self, filename): | |
| '''Get file extension.''' | |
| return path.splitext(filename)[1].lower() | |
| def zipfile(self, filename): | |
| '''Zip specified file and remove it.''' | |
| fileext = self.get_fileext(filename) | |
| if fileext in self.excluded_exts: | |
| return | |
| zipfilename = filename + '.zip' | |
| basename = path.basename(filename) | |
| with zipfile.ZipFile(zipfilename, 'w') as zfd: | |
| zfd.write(filename, basename) | |
| remove(filename) | |
| def unzipfile(self, zipfilename): | |
| '''Unzip specified file and remove it.''' | |
| fileext = self.get_fileext(zipfilename) | |
| if fileext != '.zip': | |
| return | |
| filename = zipfilename[:-len('.zip')] | |
| basename = path.basename(filename) | |
| dirname = path.dirname(filename) | |
| successed = False | |
| with zipfile.ZipFile(zipfilename, 'r') as zfd: | |
| filelist = zfd.namelist() | |
| if len(filelist) == 1 and filelist[0] == basename: | |
| zfd.extract(basename, dirname) | |
| successed = True | |
| if successed: | |
| remove(zipfilename) | |
| def run(self): | |
| '''Main entry of application''' | |
| action = self.zipfile if self.args.subcmd == 'zip' else self.unzipfile | |
| for folder in self.args.folder: | |
| for root, dirs, files in walk(folder): | |
| for filename in files: | |
| try: | |
| action(path.join(root, filename)) | |
| except Exception as e: | |
| print e | |
| if __name__ == '__main__': | |
| App(sys.argv[1:]).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment