Last active
August 17, 2021 23:45
-
-
Save fgshun/adfa508b16d62e65c8861b0ed540ec7f to your computer and use it in GitHub Desktop.
example of using python zipfile module.
This file contains 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
import argparse | |
import logging | |
import zipfile | |
from pathlib import Path | |
logger = logging.getLogger(__name__) | |
class Error(Exception): | |
pass | |
def archive(target: Path): | |
dest = target.with_name(target.name + '.zip') | |
if dest == target: | |
raise Error(f'input: {dest} equal output.') | |
elif dest.exists(): | |
raise Error(f'input: {dest} is exists.') | |
logger.info('write %s', dest) | |
with zipfile.ZipFile(dest, 'w', compression=zipfile.ZIP_STORED) as zf: | |
for f in _itertarget(target): | |
with f.open('rb') as b: | |
data = b.read() | |
p = str(f.relative_to(target.parent)) | |
logger.info('add %s', p) | |
zf.writestr(p, data) | |
def _itertarget(target: Path): | |
if target.is_file(): | |
yield target | |
elif target.is_dir(): | |
yield from (t for t in target.rglob('*') if t.is_file()) | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('src', type=Path, nargs='+') | |
args = parser.parse_args() | |
for p in args.src: | |
try: | |
archive(p) | |
except Error as e: | |
logger.warning(f'{e} skipped.') | |
if __name__ == '__main__': | |
logging.basicConfig(level=logging.INFO) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment