my_zip_file.py 843 B

123456789101112131415161718192021222324
  1. #!/usr/bin/python3
  2. #
  3. #A function that creates a archive with a truncated directory tree
  4. import os, glob, zipfile, shutil
  5. def archiver(path):
  6. '''Create a Zip archive, truncated to the basename of its path'''
  7. archive_name = os.path.abspath(os.path.basename(path) + '.zip')
  8. zf = zipfile.ZipFile(archive_name, 'w')
  9. inventory = glob.glob(os.path.join(path, '*'))
  10. for item in inventory:
  11. if os.path.isfile(item):
  12. base = os.path.basename(os.path.dirname(item))
  13. source = os.path.basename(item)
  14. join = os.path.join(base, source)
  15. try:
  16. zf.write(join)
  17. except:
  18. if not os.path.exists(base):
  19. os.mkdir(base)
  20. shutil.copy(item, base)
  21. zf.write(join)
  22. shutil.rmtree(base)