Guest User

Untitled

a guest
Jan 17th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. import os
  2. import os.path as op
  3. import shutil
  4. import tempfile
  5. import subprocess
  6.  
  7.  
  8. def create_zip(files, password=None):
  9. """
  10. Args:
  11. files: e.g. [{"filename": "a.txt", "content": "hello"}, {"filename": "a/b.txt", "content": "world"}]
  12.  
  13. Example:
  14. zdata = create_zip([{"filename": "a.txt", "content": "hello"}, {"filename": "a/b.txt", "content": "world"}], password='123')
  15. open('/tmp/t.zip', 'w').write(zdata)
  16. """
  17. temp_dir = tempfile.mkdtemp()
  18.  
  19. for spec in files:
  20. filename = op.join(temp_dir, spec['filename'])
  21. dirname = op.dirname(filename)
  22. if not op.exists(dirname):
  23. os.makedirs(dirname)
  24. open(filename, 'wb').write(spec['content'])
  25.  
  26. ar_path = op.join(temp_dir, 'ar.zip')
  27.  
  28. cmd = [
  29. '7z', 'a', '-y', ar_path, temp_dir + '/*'
  30. ]
  31.  
  32. if password is not None:
  33. cmd.append('-p' + password)
  34.  
  35. subprocess.call(cmd)
  36.  
  37. zdata = open(ar_path).read()
  38. shutil.rmtree(temp_dir)
  39.  
  40. return zdata
Add Comment
Please, Sign In to add comment