TarIO.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # read files from within a tar file
  6. #
  7. # History:
  8. # 95-06-18 fl Created
  9. # 96-05-28 fl Open files in binary mode
  10. #
  11. # Copyright (c) Secret Labs AB 1997.
  12. # Copyright (c) Fredrik Lundh 1995-96.
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. import io
  17. import sys
  18. from . import ContainerIO
  19. ##
  20. # A file object that provides read access to a given member of a TAR
  21. # file.
  22. class TarIO(ContainerIO.ContainerIO):
  23. def __init__(self, tarfile, file):
  24. """
  25. Create file object.
  26. :param tarfile: Name of TAR file.
  27. :param file: Name of member file.
  28. """
  29. self.fh = open(tarfile, "rb")
  30. while True:
  31. s = self.fh.read(512)
  32. if len(s) != 512:
  33. raise IOError("unexpected end of tar file")
  34. name = s[:100].decode("utf-8")
  35. i = name.find("\0")
  36. if i == 0:
  37. raise IOError("cannot find subfile")
  38. if i > 0:
  39. name = name[:i]
  40. size = int(s[124:135], 8)
  41. if file == name:
  42. break
  43. self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
  44. # Open region
  45. ContainerIO.ContainerIO.__init__(self, self.fh, self.fh.tell(), size)
  46. # Context manager support
  47. def __enter__(self):
  48. return self
  49. def __exit__(self, *args):
  50. self.close()
  51. if sys.version_info.major >= 3:
  52. def __del__(self):
  53. self.close()
  54. def close(self):
  55. self.fh.close()