TarIO.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. msg = "unexpected end of tar file"
  31. raise OSError(msg)
  32. name = s[:100].decode("utf-8")
  33. i = name.find("\0")
  34. if i == 0:
  35. msg = "cannot find subfile"
  36. raise OSError(msg)
  37. if i > 0:
  38. name = name[:i]
  39. size = int(s[124:135], 8)
  40. if file == name:
  41. break
  42. self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
  43. # Open region
  44. super().__init__(self.fh, self.fh.tell(), size)
  45. # Context manager support
  46. def __enter__(self):
  47. return self
  48. def __exit__(self, *args):
  49. self.close()
  50. def close(self):
  51. self.fh.close()