TarIO.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. from . import ContainerIO
  18. class TarIO(ContainerIO.ContainerIO):
  19. """A file object that provides read access to a given member of a TAR file."""
  20. def __init__(self, tarfile, file):
  21. """
  22. Create file object.
  23. :param tarfile: Name of TAR file.
  24. :param file: Name of member file.
  25. """
  26. self.fh = open(tarfile, "rb")
  27. while True:
  28. s = self.fh.read(512)
  29. if len(s) != 512:
  30. raise OSError("unexpected end of tar file")
  31. name = s[:100].decode("utf-8")
  32. i = name.find("\0")
  33. if i == 0:
  34. raise OSError("cannot find subfile")
  35. if i > 0:
  36. name = name[:i]
  37. size = int(s[124:135], 8)
  38. if file == name:
  39. break
  40. self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
  41. # Open region
  42. super().__init__(self.fh, self.fh.tell(), size)
  43. # Context manager support
  44. def __enter__(self):
  45. return self
  46. def __exit__(self, *args):
  47. self.close()
  48. def close(self):
  49. self.fh.close()