Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import zipfile
  2. from io import BytesIO
  3.  
  4.  
  5. def zipwalk(current_file, file_handling_func, curr_path='/'):
  6. """Recursively walks into a zipped file.
  7.  
  8. Arguments:
  9. ----------
  10. - current_file : file
  11. a file object opened in `read-bytes` mode
  12.  
  13. - file_handling_func : function
  14. function to handle a non-zip file content.
  15. zipwalk will call it with the following arguments:
  16. - content: io.BytesIO
  17. - zip_file_object: zipfile.ZipExtFile (not a zipped file itself).
  18. - path : string
  19.  
  20. - curr_path : string
  21. the current path inside outmost zip file.
  22. """
  23. content = BytesIO(current_file.read())
  24. if zipfile.is_zipfile(content):
  25. subzip = zipfile.ZipFile(content)
  26.  
  27. # recurse
  28. return [
  29. zipwalk(
  30. subzip.open(i.filename),
  31. file_handling_func,
  32. curr_path + current_file.name + '/'
  33. )
  34. for i in subzip.filelist
  35. ]
  36.  
  37. else:
  38. # handle non-zip file contents
  39. file_handling_func(content, current_file, curr_path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement