Aluode/PerceptionLabPortable
0
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#
16from __future__ import annotations
17
18import io
19
20from . import ContainerIO
21
22
23class TarIO(ContainerIO.ContainerIO[bytes]):
24 """A file object that provides read access to a given member of a TAR file."""
25
26 def __init__(self, tarfile: str, file: str) -> None:
27 """
28 Create file object.
29
30 :param tarfile: Name of TAR file.
31 :param file: Name of member file.
32 """
33 self.fh = open(tarfile, "rb")
34
35 while True:
36 s = self.fh.read(512)
37 if len(s) != 512:
38 self.fh.close()
39
40 msg = "unexpected end of tar file"
41 raise OSError(msg)
42
43 name = s[:100].decode("utf-8")
44 i = name.find("\0")
45 if i == 0:
46 self.fh.close()
47
48 msg = "cannot find subfile"
49 raise OSError(msg)
50 if i > 0:
51 name = name[:i]
52
53 size = int(s[124:135], 8)
54
55 if file == name:
56 break
57
58 self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
59
60 # Open region
61 super().__init__(self.fh, self.fh.tell(), size)
62 