Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import os.path as op
- import shutil
- import tempfile
- import subprocess
- def create_zip(files, password=None):
- """
- Args:
- files: e.g. [{"filename": "a.txt", "content": "hello"}, {"filename": "a/b.txt", "content": "world"}]
- Example:
- zdata = create_zip([{"filename": "a.txt", "content": "hello"}, {"filename": "a/b.txt", "content": "world"}], password='123')
- open('/tmp/t.zip', 'w').write(zdata)
- """
- temp_dir = tempfile.mkdtemp()
- for spec in files:
- filename = op.join(temp_dir, spec['filename'])
- dirname = op.dirname(filename)
- if not op.exists(dirname):
- os.makedirs(dirname)
- open(filename, 'wb').write(spec['content'])
- ar_path = op.join(temp_dir, 'ar.zip')
- cmd = [
- '7z', 'a', '-y', ar_path, temp_dir + '/*'
- ]
- if password is not None:
- cmd.append('-p' + password)
- subprocess.call(cmd)
- zdata = open(ar_path).read()
- shutil.rmtree(temp_dir)
- return zdata
Add Comment
Please, Sign In to add comment