"tarfile" --- tar アーカイブファイルの読み書き
**********************************************

**ソースコード:** Lib/tarfile.py

======================================================================

"tarfile" モジュールは、gzip、bz2、および lzma 圧縮されたものを含む、
tar アーカイブを読み書きできます。".zip" ファイルの読み書きには
"zipfile" モジュールか、あるいは shutil の高水準関数を使用してください
。

いくつかの事実と形態:

* モジュールが利用可能な場合、"gzip"、"bz2" ならびに "lzma" で圧縮され
  たアーカイブを読み書きします。

* POSIX.1-1988 (ustar) フォーマットの読み書きをサポートしています。

* *longname* および *longlink* 拡張を含む GNU tar フォーマットの読み書
  きをサポートしています。スパースファイルの復元を含む *sparse* 拡張は
  読み込みのみサポートしています。

* POSIX.1-2001 (pax) フォーマットの読み書きをサポートしています。

* ディレクトリ、一般ファイル、ハードリンク、シンボリックリンク、fifo、
  キャラクターデバイスおよびブロックデバイスを処理します。また、タイム
  スタンプ、アクセス許可や所有者のようなファイル情報の取得および保存が
  可能です。

バージョン 3.3 で変更: "lzma" 圧縮をサポートしました。

tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

   パス名 *name* の "TarFile" オブジェクトを返します。"TarFile" オブジ
   ェクトと、利用できるキーワード引数に関する詳細な情報については、
   TarFile オブジェクト 節を参照してください。

   *mode* は "'filemode[:compression]'" の形式をとる文字列でなければな
   りません。デフォルトの値は "'r'" です。以下に *mode* のとりうる組み
   合わせすべてを示します:

   +--------------------+-----------------------------------------------+
   | mode               | action                                        |
   |====================|===============================================|
   | "'r' または 'r:*'" | 圧縮方法に関して透過的に、読み込み用にオープ  |
   |                    | ンします (推奨)。                             |
   +--------------------+-----------------------------------------------+
   | "'r:'"             | 非圧縮で読み込み用に排他的にオープンします。  |
   +--------------------+-----------------------------------------------+
   | "'r:gz'"           | gzip 圧縮で読み込み用にオープンします。       |
   +--------------------+-----------------------------------------------+
   | "'r:bz2'"          | bzip2 圧縮で読み込み用にオープンします。      |
   +--------------------+-----------------------------------------------+
   | "'r:xz'"           | lzma 圧縮で読み込み用にオープンします。       |
   +--------------------+-----------------------------------------------+
   | "'x'" or "'x:'"    | 圧縮せずに tarfile を排他的に作成します。     |
   |                    | tarfile が既存の場合 "FileExistsError" 例外を |
   |                    | 送出します。                                  |
   +--------------------+-----------------------------------------------+
   | "'x:gz'"           | gzip 圧縮で tarfile を作成します。tarfile が  |
   |                    | 既存の場合 "FileExistsError" 例外を送出します |
   |                    | 。                                            |
   +--------------------+-----------------------------------------------+
   | "'x:bz2'"          | bzip2 圧縮で tarfile を作成します。tarfile が |
   |                    | 既存の場合 "FileExistsError" 例外を送出します |
   |                    | 。                                            |
   +--------------------+-----------------------------------------------+
   | "'x:xz'"           | lzma 圧縮で tarfile を作成します。tarfile が  |
   |                    | 既存の場合 "FileExistsError" 例外を送出します |
   |                    | 。                                            |
   +--------------------+-----------------------------------------------+
   | "'a' または 'a:'"  | 非圧縮で追記用にオープンします。ファイルが存  |
   |                    | 在しない場合は新たに作 成されます。           |
   +--------------------+-----------------------------------------------+
   | "'w' または 'w:'"  | 非圧縮で書き込み用にオープンします。          |
   +--------------------+-----------------------------------------------+
   | "'w:gz'"           | gzip 圧縮で書き込み用にオープンします。       |
   +--------------------+-----------------------------------------------+
   | "'w:bz2'"          | bzip2 圧縮で書き込み用にオープンします。      |
   +--------------------+-----------------------------------------------+
   | "'w:xz'"           | lzma 圧縮で書き込み用にオープンします。       |
   +--------------------+-----------------------------------------------+

   "'a:gz'"、"'a:bz2'"、"'a:xz'" は利用できないことに注意して下さい。
   もし *mode* が、ある (圧縮した) ファイルを読み込み用にオープンする
   のに適していないなら、"ReadError" が送出されます。これを防ぐには
   *mode* "'r'" を使って下さい。もし圧縮方式がサポートされていなければ
   、"CompressionError" が送出されます。

   もし *fileobj* が指定されていれば、それは *name* でバイナリモードで
   オープンされた *ファイルオブジェクト* の代替として使うことができま
   す。そのファイルオブジェクトの位置が 0 であることを前提に動作します
   。

   "'w:gz'"、"'r:gz'"、"'w:bz2'"、"'r:bz2'", "'x:gz'", "'x:bz2'" モー
   ドの場合、"tarfile.open()" はファイルの圧縮レベルを指定するキーワー
   ド引数 *compresslevel* (デフォルトは "9") を受け付けます。

   "'w:xz'" および "'x:xz'" モードの場合、"tarfile.open()" はファイル
   の圧縮レベルを指定するキーワード引数 *preset* を受け付けます。

   特別な目的のために、*mode* には 2 番目の形式: "'ファイルモード|[圧
   縮]'" があります。この形式を使うと、"tarfile.open()" が返すのは、デ
   ータをブロックからなるストリームとして扱う "TarFile" オブジェクトに
   なります。この場合、ファイルに対してランダムなシークが行えなくなり
   ます。*fileobj* を指定する場合、 "read()" および "write()" メソッド
   を持つ (*mode* に依存した) 任意のオブジェクトにできます。*bufsize*
   にはブロックサイズを指定します。デフォルトは "20 * 512" バイトです
   。"sys.stdin"、ソケット *file object*、あるいはテープデバイスと組み
   合わせる場合にはこの形式を使ってください。ただし、このような
   "TarFile" オブジェクトにはランダムアクセスを行えないという制限があ
   ります。使用例 節を参照してください。現在可能なモードは以下のとおり
   です。

   +---------------+----------------------------------------------+
   | モード        | 動作                                         |
   |===============|==============================================|
   | "'r|*'"       | tar ブロックの *stream* を圧縮方法に関して透 |
   |               | 過的に読み込み用にオー プンします。          |
   +---------------+----------------------------------------------+
   | "'r|'"        | 非圧縮 tar ブロックの *stream* を読み込み用  |
   |               | にオープンします。                           |
   +---------------+----------------------------------------------+
   | "'r|gz'"      | gzip 圧縮の *stream* を読み込み用にオープン  |
   |               | します。                                     |
   +---------------+----------------------------------------------+
   | "'r|bz2'"     | bzip2 圧縮の *stream* を読み込み用にオープン |
   |               | します。                                     |
   +---------------+----------------------------------------------+
   | "'r|xz'"      | lzma 圧縮の *stream* を読み込み用にオープン  |
   |               | します。                                     |
   +---------------+----------------------------------------------+
   | "'w|'"        | 非圧縮の *stream* を書き込み用にオープンしま |
   |               | す。                                         |
   +---------------+----------------------------------------------+
   | "'w|gz'"      | gzip 圧縮の *stream* を書き込み用にオープン  |
   |               | します。                                     |
   +---------------+----------------------------------------------+
   | "'w|bz2'"     | bzip2 圧縮の *stream* を書き込み用にオープン |
   |               | します。                                     |
   +---------------+----------------------------------------------+
   | "'w|xz'"      | lzma 圧縮の *stream* を書き込み用にオープン  |
   |               | します。                                     |
   +---------------+----------------------------------------------+

   バージョン 3.5 で変更: "'x'" (排他的作成) モードが追加されました。

   バージョン 3.6 で変更: *name* パラメタが *path-like object* を受け
   付けるようになりました。

class tarfile.TarFile

   tar アーカイブを読み書きするためのクラスです。このクラスを直接使わ
   ないこと: 代わりに "tarfile.open()" を使ってください。TarFile オブ
   ジェクト を参照してください。

tarfile.is_tarfile(name)

   もし *name* が tar アーカイブファイルであり、"tarfile" モジュールで
   読み込める場合に "True" を返します。 *name* は文字列、ファイルまた
   は file-like オブジェクトです。

   バージョン 3.9 で変更: ファイルおよびファイルライクオブジェクトをサ
   ポートしました。

"tarfile" モジュールは以下の例外を定義しています:

exception tarfile.TarError

   すべての "tarfile" 例外のための基本クラスです。

exception tarfile.ReadError

   tar アーカイブがオープンされた時、"tarfile" モジュールで操作できな
   いか、あるいは何か無効であるとき送出されます。

exception tarfile.CompressionError

   圧縮方法がサポートされていないか、あるいはデータを正しくデコードで
   きない時に送出されます。

exception tarfile.StreamError

   ストリームのような "TarFile" オブジェクトで典型的な制限のために送出
   されます。

exception tarfile.ExtractError

   "TarFile.extract()" を使った時に *致命的でない* エラーに対して送出
   されます。ただし "TarFile.errorlevel""== 2" の場合に限ります。

exception tarfile.HeaderError

   "TarInfo.frombuf()" メソッドが取得したバッファーが不正だったときに
   送出されます。

exception tarfile.FilterError

   Base class for members refused by filters.

   tarinfo

      Information about the member that the filter refused to extract,
      as TarInfo.

exception tarfile.AbsolutePathError

   Raised to refuse extracting a member with an absolute path.

exception tarfile.OutsideDestinationError

   Raised to refuse extracting a member outside the destination
   directory.

exception tarfile.SpecialFileError

   Raised to refuse extracting a special file (e.g. a device or pipe).

exception tarfile.AbsoluteLinkError

   Raised to refuse extracting a symbolic link with an absolute path.

exception tarfile.LinkOutsideDestinationError

   Raised to refuse extracting a symbolic link pointing outside the
   destination directory.

exception tarfile.LinkFallbackError

   Raised to refuse emulating a link (hard or symbolic) by extracting
   another archive member, when that member would be rejected by the
   filter location. The exception that was raised to reject the
   replacement member is available as "BaseException.__context__".

   バージョン 3.9.24 (unreleased) で追加.

モジュールレベルで以下の定数が利用できます。

tarfile.ENCODING

   既定の文字エンコーディング。Windows では "'utf-8'" 、それ以外では
   "sys.getfilesystemencoding()" の返り値です。

以下の各定数は、"tarfile" モジュールが作成できる tar アーカイブフォー
マットを定義しています。詳細は、サポートしている tar フォーマット を参
照してください。

tarfile.USTAR_FORMAT

   POSIX.1-1988 (ustar) フォーマット。

tarfile.GNU_FORMAT

   GNU tar フォーマット。

tarfile.PAX_FORMAT

   POSIX.1-2001 (pax) フォーマット。

tarfile.DEFAULT_FORMAT

   アーカイブを作成する際のデフォルトのフォーマット。現在は
   "PAX_FORMAT" です。

   バージョン 3.8 で変更: 新しいアーカイブのデフォルトフォーマットが
   "GNU_FORMAT" から "PAX_FORMAT" に変更されました。

参考:

  "zipfile" モジュール
     "zipfile" 標準モジュールのドキュメント。

  アーカイブ化操作
     "shutil" が提供するより高水準のアーカイブ機能についてのドキュメン
     ト。

  GNU tar manual, Basic Tar Format
     GNU tar 拡張機能を含む、tar アーカイブファイルのためのドキュメン
     ト。


TarFile オブジェクト
====================

"TarFile" オブジェクトは、tar アーカイブへのインターフェースを提供しま
す。tar アーカイブは一連のブロックです。アーカイブメンバー (保存された
ファイル) は、ヘッダーブロックとそれに続くデータブロックで構成されてい
ます。一つの tar アーカイブにファイルを何回も保存することができます。
各アーカイブメンバーは、"TarInfo" オブジェクトで確認できます。詳細につ
いては TarInfo オブジェクト を参照してください。

"TarFile" オブジェクトは "with" 文のコンテキストマネージャーとして利用
できます。with ブロックが終了したときにオブジェクトはクローズされます
。例外が発生した時、内部で利用されているファイルオブジェクトのみがクロ
ーズされ、書き込み用にオープンされたアーカイブのファイナライズは行われ
ないことに注意してください。使用例 節のユースケースを参照してください
。

バージョン 3.2 で追加: コンテキスト管理のプロトコルがサポートされまし
た。

class tarfile.TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=1)

   以下のすべての引数はオプションで、インスタンス属性としてもアクセス
   できます。

   *name* はアーカイブのパス名です。*name* は *path-like object* でも
   構いません。*fileobj* が渡された場合は省略可能です。その場合、ファ
   イルオブジェクトに "name" 属性があれば、それを利用します。

   *mode* は、既存のアーカイブから読み込むための "'r'"、既存のアーカイ
   ブに追記するための "'a'"、既存のファイルがあれば上書きして新しいフ
   ァイルを作成する "'w'" 、あるいは存在しない場合にのみ新しいファイル
   を作成する "'x'" のいずれかです。

   *fileobj* が与えられていれば、それを使ってデータを読み書きします。
   もしそれが決定できれば、*mode* は *fileobj* のモードで上書きされま
   す。*fileobj* は位置 0 から利用されます。

   注釈:

     "TarFile" をクローズした時、*fileobj* はクローズされません。

   *format* はアーカイブの書き込みフォーマットを制御します。モジュール
   レベルで定義されている、"USTAR_FORMAT"、"GNU_FORMAT"、あるいは
   "PAX_FORMAT" のいずれかである必要があります。 読み出しのときは、1
   つのアーカイブに異なるフォーマットが混在していたとしても、フォーマ
   ットは自動的に検知されます。

   *tarinfo* 引数を利用して、デフォルトの "TarInfo" クラスを別のクラス
   で置き換えることができます。

   *dereference* が "False" だった場合、シンボリックリンクやハードリン
   クがアーカイブに追加されます。"True" だった場合、リンクのターゲット
   となるファイルの内容がアーカイブに追加されます。シンボリックリンク
   をサポートしていないシステムでは効果がありません。

   *ignore_zeros* が "False" だった場合、空ブロックをアーカイブの終端
   として扱います。"True" だった場合、空の (無効な) ブロックをスキップ
   して、可能な限り多くのメンバーを取得しようとします。このオプション
   は、連結されたり、壊れたアーカイブファイルを扱うときにのみ、意味が
   あります。

   *debug* は "0" (デバッグメッセージ無し) から "3" (全デバッグメッセ
   ージ) まで設定できます。このメッセージは "sys.stderr" に書き込まれ
   ます。

   *errorlevel* controls how extraction errors are handled, see "the
   corresponding attribute".

   引数 *encoding* および *errors* にはアーカイブの読み書きやエラー文
   字列の変換に使用する文字エンコーディングを指定します。ほとんどのユ
   ーザーはデフォルト設定のままで動作します。詳細に関しては Unicode に
   関する問題 節を参照してください。

   引数 *pax_headers* は、オプションの文字列辞書で、*format* が
   "PAX_FORMAT" だった場合に pax グローバルヘッダーに追加されます。

   バージョン 3.2 で変更: 引数 *errors* のデフォルトが
   "'surrogateescape'" になりました。

   バージョン 3.5 で変更: "'x'" (排他的作成) モードが追加されました。

   バージョン 3.6 で変更: *name* パラメタが *path-like object* を受け
   付けるようになりました。

classmethod TarFile.open(...)

   代替コンストラクターです。モジュールレベルでの "tarfile.open()" 関
   数は、実際はこのクラスメソッドへのショートカットです。

TarFile.getmember(name)

   メンバー *name* に対する "TarInfo" オブジェクトを返します。*name*
   がアーカイブに見つからなければ、"KeyError" が送出されます。

   注釈:

     アーカイブ内にメンバーが複数ある場合は、最後に出現するものが最新
     のバージョンとみなされます。

TarFile.getmembers()

   "TarInfo" アーカイブのメンバーをオブジェクトのリストとして返します
   。このリストはアーカイブ内のメンバーと同じ順番です。

TarFile.getnames()

   メンバーをその名前のリストを返します。これは "getmembers()" で返さ
   れるリストと同じ順番です。

TarFile.list(verbose=True, *, members=None)

   内容の一覧を "sys.stdout" に出力します。*verbose* が "False" の場合
   、メンバー名のみ表示します。"True" の場合、 **ls -l** に似た出力を
   生成します。オプションの *members* を与える場合、 "getmembers()" が
   返すリストのサブセットである必要があります。

   バージョン 3.5 で変更: *members* 引数が追加されました。.

TarFile.next()

   "TarFile" が読み込み用にオープンされている時、アーカイブの次のメン
   バーを "TarInfo" オブジェクトとして返します。もしそれ以上利用可能な
   ものがなければ、"None" を返します。

TarFile.extractall(path=".", members=None, *, numeric_owner=False, filter=None)

   すべてのメンバーをアーカイブから現在の作業ディレクトリまたは *path*
   に抽出します。オプションの *members* が与えられるときには、
   "getmembers()" で返されるリストの一部でなければなりません。所有者、
   変更時刻、アクセス権限のようなディレクトリ情報はすべてのメンバーが
   抽出された後にセットされます。これは二つの問題を回避するためです。
   一つはディレクトリの変更時刻はその中にファイルが作成されるたびにリ
   セットされるということ、もう一つはディレクトリに書き込み許可がなけ
   ればその中のファイル抽出は失敗してしまうということです。

   *numeric_owner* が "True" の場合、tarfile の uid と gid 数値が抽出
   されたファイルのオーナー/グループを設定するために使用されます。
   False の場合、tarfile の名前付きの値が使用されます。

   The *filter* argument, which was added in Python 3.9.17, specifies
   how "members" are modified or rejected before extraction. See
   Extraction filters for details. It is recommended to set this
   explicitly depending on which *tar* features you need to support.

   警告:

     内容を信頼できない tar アーカイブを、事前の内部チェック前に展開し
     てはいけません。ファイルが *path* の外側に作られる可能性がありま
     す。例えば、""/"" で始まる絶対パスのファイル名や、2 重ドット
     "".."" で始まるパスのファイル名です。Set "filter='data'" to
     prevent the most dangerous security issues, and read the
     Extraction filters section for details.

   バージョン 3.5 で変更: *numeric_owner* 引数が追加されました。

   バージョン 3.6 で変更: *path* パラメタが *path-like object* を受け
   付けるようになりました。

   バージョン 3.9.17 で変更: *filter* パラメータが追加されました。

TarFile.extract(member, path="", set_attrs=True, *, numeric_owner=False, filter=None)

   アーカイブからメンバーの完全な名前を使って、現在のディレクトリに展
   開します。ファイル情報はできる限り正確に展開されます。 *member* は
   ファイル名もしくは "TarInfo" オブジェクトです。 *path* を使って別の
   ディレクトリを指定することもできます。 *path* は　*path-like
   object* でも構いません。*set_attrs* が false でない限り、ファイルの
   属性 (所有者、最終更新時刻、モード) は設定されます。

   The *numeric_owner* and *filter* arguments are the same as for
   "extractall()".

   注釈:

     "extract()" メソッドはいくつかの展開に関する問題を扱いません。ほ
     とんどの場合、"extractall()" メソッドの利用を考慮するべきです。

   警告:

     "extractall()" の警告を参してください。Set "filter='data'" to
     prevent the most dangerous security issues, and read the
     Extraction filters section for details.

   バージョン 3.2 で変更: パラメーターに *set_attrs* を追加しました。

   バージョン 3.5 で変更: *numeric_owner* 引数が追加されました。

   バージョン 3.6 で変更: *path* パラメタが *path-like object* を受け
   付けるようになりました。

   バージョン 3.9.17 で変更: *filter* パラメータが追加されました。

TarFile.extractfile(member)

   アーカイブからメンバーをファイルオブジェクトとして抽出します。
   *member* はファイル名でも "TarInfo" オブジェクトでも構いません。
   *member* が一般ファイルまたはリンクの場合、"io.BufferedReader" オブ
   ジェクトが返されます。 存在するそれ以外のメンバーでは、 "None" が返
   されます。 それ以外の場合、"None" が返されます。 アーカイブに
   *member* が存在しない場合は "KeyError" が送出されます。

   バージョン 3.3 で変更: 戻り値が "io.BufferedReader" オブジェクトに
   なりました。

TarFile.errorlevel: int

   If *errorlevel* is "0", errors are ignored when using
   "TarFile.extract()" and "TarFile.extractall()". Nevertheless, they
   appear as error messages in the debug output when *debug* is
   greater than 0. If "1" (the default), all *fatal* errors are raised
   as "OSError" or "FilterError" exceptions. If "2", all *non-fatal*
   errors are raised as "TarError" exceptions as well.

   Some exceptions, e.g. ones caused by wrong argument types or data
   corruption, are always raised.

   Custom extraction filters should raise "FilterError" for *fatal*
   errors and "ExtractError" for *non-fatal* ones.

   Note that when an exception is raised, the archive may be partially
   extracted. It is the user’s responsibility to clean up.

TarFile.extraction_filter

   バージョン 3.9.17 で追加.

   The extraction filter used as a default for the *filter* argument
   of "extract()" and "extractall()".

   The attribute may be "None" or a callable. String names are not
   allowed for this attribute, unlike the *filter* argument to
   "extract()".

   If "extraction_filter" is "None" (the default), calling an
   extraction method without a *filter* argument will use the
   "fully_trusted" filter for compatibility with previous Python
   versions.

   In Python 3.12+, leaving "extraction_filter=None" will emit a
   "DeprecationWarning".

   In Python 3.14+, leaving "extraction_filter=None" will cause
   extraction methods to use the "data" filter by default.

   The attribute may be set on instances or overridden in subclasses.
   It also is possible to set it on the "TarFile" class itself to set
   a global default, although, since it affects all uses of *tarfile*,
   it is best practice to only do so in top-level applications or
   "site configuration". To set a global default this way, a filter
   function needs to be wrapped in "staticmethod()" to prevent
   injection of a "self" argument.

TarFile.add(name, arcname=None, recursive=True, *, filter=None)

   ファイル *name* をアーカイブに追加します。 *name* は、任意のファイ
   ルタイプ (ディレクトリ、fifo、シンボリックリンク等)です。 *arcname*
   が与えられている場合は、それはアーカイブ内のファイルの代替名を指定
   します。 デフォルトではディレクトリは再帰的に追加されます。 これは
   、 *recursive* を "False" に設定すると避けられます。 再帰処理はソー
   トされた順序でエントリーを追加します。 *filter* が与えられた場合、
   それは "TarInfo" オブジェクトを引数として受け取り、操作した
   "TarInfo" オブジェクトを返す関数でなければなりません。 代わりに
   "None" を返した場合、 "TarInfo" オブジェクトはアーカイブから除外さ
   れます。 使用例 にある例を参照してください。

   バージョン 3.2 で変更: *filter* パラメータが追加されました。

   バージョン 3.7 で変更: 再帰処理はソートされた順序でエントリーを追加
   するようになりました。

TarFile.addfile(tarinfo, fileobj=None)

   "TarInfo" オブジェクト *tarinfo* をアーカイブに追加します。
   *fileobj* を与える場合、*binary file* にしなければならず、
   "tarinfo.size" バイトがそれから読まれ、アーカイブに追加されます。
   "TarInfo" オブジェクトを直接作成するか、"gettarinfo()" を使って作成
   することができます。

TarFile.gettarinfo(name=None, arcname=None, fileobj=None)

   "os.stat()" の結果か、既存のファイルに相当するものから、"TarInfo"
   オブジェクトを作成します。このファイルは、*name* で名付けられるか、
   ファイル記述子を持つ *file object* *fileobj* として指定されます。
   *name* は:term:*path-like object* でも構いません。 *arcname* が与え
   られた場合、アーカイブ内のファイルに対して代替名を指定します。与え
   られない場合、名前は *fileobj* の "name" 属性 *name* 属性から取られ
   ます。名前はテキスト文字列にしてください。

   "TarInfo" の属性の一部は、"addfile()" を使用して追加する前に修正で
   きます。ファイルオブジェクトが、ファイルの先頭にある通常のファイル
   オブジェクトでない場合、 "size" などの属性は修正が必要かもしれませ
   ん。これは、 "GzipFile" などの属性に当てはまります。"name" も修正で
   きるかもしれず、この場合、*arcname* はダミーの文字列にすることがで
   きます。

   バージョン 3.6 で変更: *name* パラメタが *path-like object* を受け
   付けるようになりました。

TarFile.close()

   "TarFile" をクローズします。書き込みモードでは、完了ゼロブロックが
   2 個アーカイブに追加されます。

TarFile.pax_headers

   pax グローバルヘッダーに含まれる key-value ペアの辞書です。


TarInfo オブジェクト
====================

"TarInfo" オブジェクトは "TarFile" の一つのメンバーを表します。ファイ
ルに必要なすべての属性 (ファイルタイプ、ファイルサイズ、時刻、アクセス
権限、所有者等のような) を保存する他に、そのタイプを決定するのに役に立
ついくつかのメソッドを提供します。これにはファイルのデータそのものは *
含まれません* 。

"TarInfo" objects are returned by "TarFile"'s methods "getmember()",
"getmembers()" and "gettarinfo()".

Modifying the objects returned by "getmember()" or "getmembers()" will
affect all subsequent operations on the archive. For cases where this
is unwanted, you can use "copy.copy()" or call the "replace()" method
to create a modified copy in one step.

Several attributes can be set to "None" to indicate that a piece of
metadata is unused or unknown. Different "TarInfo" methods handle
"None" differently:

* The "extract()" or "extractall()" methods will ignore the
  corresponding metadata, leaving it set to a default.

* "addfile()" will fail.

* "list()" will print a placeholder string.

バージョン 3.9.17 で変更: Added "replace()" and handling of "None".

class tarfile.TarInfo(name="")

   "TarInfo" オブジェクトを作成します。

classmethod TarInfo.frombuf(buf, encoding, errors)

   "TarInfo" オブジェクトを文字列バッファー *buf* から作成して返します
   。

   バッファーが不正な場合 "HeaderError" を送出します。

classmethod TarInfo.fromtarfile(tarfile)

   "TarFile" オブジェクトの *tarfile* から、次のメンバーを読み込んで、
   それを "TarInfo" オブジェクトとして返します。

TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')

   "TarInfo" オブジェクトから文字列バッファーを作成します。引数につい
   ての情報は、"TarFile" クラスのコンストラクターを参照してください。

   バージョン 3.2 で変更: 引数 *errors* のデフォルトが
   "'surrogateescape'" になりました。

"TarInfo" オブジェクトには以下のデータ属性があります:

TarInfo.name: str

   アーカイブメンバーの名前。

TarInfo.size: int

   バイト単位でのサイズ。

TarInfo.mtime: int | float

   Time of last modification in seconds since the epoch, as in
   "os.stat_result.st_mtime".

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.mode: int

   Permission bits, as for "os.chmod()".

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.type

   ファイルタイプ。*type* は通常、定数 "REGTYPE"、"AREGTYPE"、
   "LNKTYPE"、"SYMTYPE"、"DIRTYPE"、"FIFOTYPE"、"CONTTYPE"、"CHRTYPE"
   、"BLKTYPE"、あるいは "GNUTYPE_SPARSE" のいずれかです。"TarInfo" オ
   ブジェクトのタイプをもっと簡単に解決するには、下記の "is*()" メソッ
   ドを使って下さい。

TarInfo.linkname: str

   リンク先ファイルの名前。これはタイプ "LNKTYPE" と "SYMTYPE" の
   "TarInfo" オブジェクトにだけ存在します。

   For symbolic links ("SYMTYPE"), the *linkname* is relative to the
   directory that contains the link. For hard links ("LNKTYPE"), the
   *linkname* is relative to the root of the archive.

TarInfo.uid: int

   ファイルメンバーを保存した元のユーザーのユーザー ID。

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.gid: int

   ファイルメンバーを保存した元のユーザーのグループ ID。

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.uname: str

   ファイルメンバーを保存した元のユーザーのユーザー名。

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.gname: str

   ファイルメンバーを保存した元のユーザーのグループ名。

   バージョン 3.9.17 で変更: Can be set to "None" for "extract()" and
   "extractall()", causing extraction to skip applying this attribute.

TarInfo.pax_headers: dict

   pax 拡張ヘッダーに関連付けられた、key-value ペアの辞書。

TarInfo.replace(name=..., mtime=..., mode=..., linkname=...,
uid=..., gid=..., uname=..., gname=...,
deep=True)

   バージョン 3.9.17 で追加.

   Return a *new* copy of the "TarInfo" object with the given
   attributes changed. For example, to return a "TarInfo" with the
   group name set to "'staff'", use:

      new_tarinfo = old_tarinfo.replace(gname='staff')

   By default, a deep copy is made. If *deep* is false, the copy is
   shallow, i.e. "pax_headers" and any custom attributes are shared
   with the original "TarInfo" object.

"TarInfo" オブジェクトは便利な照会用のメソッドもいくつか提供しています
:

TarInfo.isfile()

   "Tarinfo" オブジェクトが一般ファイルの場合に、"True" を返します。

TarInfo.isreg()

   "isfile()" と同じです。

TarInfo.isdir()

   ディレクトリの場合に "True" を返します。

TarInfo.issym()

   シンボリックリンクの場合に "True" を返します。

TarInfo.islnk()

   ハードリンクの場合に "True" を返します。

TarInfo.ischr()

   キャラクターデバイスの場合に "True" を返します。

TarInfo.isblk()

   ブロックデバイスの場合に "True" を返します。

TarInfo.isfifo()

   FIFO の場合に "True" を返します。

TarInfo.isdev()

   キャラクターデバイス、ブロックデバイスあるいは FIFO のいずれかの場
   合に "True" を返します。


Extraction filters
==================

バージョン 3.9.17 で追加.

The *tar* format is designed to capture all details of a UNIX-like
filesystem, which makes it very powerful. Unfortunately, the features
make it easy to create tar files that have unintended -- and possibly
malicious -- effects when extracted. For example, extracting a tar
file can overwrite arbitrary files in various ways (e.g.  by using
absolute paths, ".." path components, or symlinks that affect later
members).

In most cases, the full functionality is not needed. Therefore,
*tarfile* supports extraction filters: a mechanism to limit
functionality, and thus mitigate some of the security issues.

参考:

  **PEP 706**
     Contains further motivation and rationale behind the design.

The *filter* argument to "TarFile.extract()" or "extractall()" can be:

* the string "'fully_trusted'": Honor all metadata as specified in the
  archive. Should be used if the user trusts the archive completely,
  or implements their own complex verification.

* the string "'tar'": Honor most *tar*-specific features (i.e.
  features of UNIX-like filesystems), but block features that are very
  likely to be surprising or malicious. See "tar_filter()" for
  details.

* the string "'data'": Ignore or block most features specific to UNIX-
  like filesystems. Intended for extracting cross-platform data
  archives. See "data_filter()" for details.

* "None" (default): Use "TarFile.extraction_filter".

  If that is also "None" (the default), the "'fully_trusted'" filter
  will be used (for compatibility with earlier versions of Python).

  In Python 3.12, the default will emit a "DeprecationWarning".

  In Python 3.14, the "'data'" filter will become the default instead.
  It's possible to switch earlier; see "TarFile.extraction_filter".

* A callable which will be called for each extracted member with a
  TarInfo describing the member and the destination path to where the
  archive is extracted (i.e. the same path is used for all members):

     filter(/, member: TarInfo, path: str) -> TarInfo | None

  The callable is called just before each member is extracted, so it
  can take the current state of the disk into account. It can:

  * return a "TarInfo" object which will be used instead of the
    metadata in the archive, or

  * return "None", in which case the member will be skipped, or

  * raise an exception to abort the operation or skip the member,
    depending on "errorlevel". Note that when extraction is aborted,
    "extractall()" may leave the archive partially extracted. It does
    not attempt to clean up.


Default named filters
---------------------

The pre-defined, named filters are available as functions, so they can
be reused in custom filters:

tarfile.fully_trusted_filter(/, member, path)

   Return *member* unchanged.

   This implements the "'fully_trusted'" filter.

tarfile.tar_filter(/, member, path)

   Implements the "'tar'" filter.

   * Strip leading slashes ("/" and "os.sep") from filenames.

   * Refuse to extract files with absolute paths (in case the name is
     absolute even after stripping slashes, e.g. "C:/foo" on Windows).
     This raises "AbsolutePathError".

   * Refuse to extract files whose absolute path (after following
     symlinks) would end up outside the destination. This raises
     "OutsideDestinationError".

   * Clear high mode bits (setuid, setgid, sticky) and group/other
     write bits ("S_IWOTH").

   Return the modified "TarInfo" member.

tarfile.data_filter(/, member, path)

   Implements the "'data'" filter. In addition to what "tar_filter"
   does:

   * Normalize link targets ("TarInfo.linkname") using
     "os.path.normpath()". Note that this removes internal ".."
     components, which may change the meaning of the link if the path
     in "TarInfo.linkname" traverses symbolic links.

   * Refuse to extract links (hard or soft) that link to absolute
     paths, or ones that link outside the destination.

     This raises "AbsoluteLinkError" or "LinkOutsideDestinationError".

     Note that such files are refused even on platforms that do not
     support symbolic links.

   * Refuse to extract device files (including pipes). This raises
     "SpecialFileError".

   * For regular files, including hard links:

     * Set the owner read and write permissions ("S_IWUSR").

     * Remove the group & other executable permission ("S_IXOTH") if
       the owner doesn’t have it ("S_IXUSR").

   * For other files (directories), set "mode" to "None", so that
     extraction methods skip applying permission bits.

   * Set user and group info ("uid", "gid", "uname", "gname") to
     "None", so that extraction methods skip setting it.

   Return the modified "TarInfo" member.

   バージョン 3.9.24 (unreleased) で変更: Link targets are now
   normalized.


Filter errors
-------------

When a filter refuses to extract a file, it will raise an appropriate
exception, a subclass of "FilterError". This will abort the extraction
if "TarFile.errorlevel" is 1 or more. With "errorlevel=0" the error
will be logged and the member will be skipped, but extraction will
continue.


Hints for further verification
------------------------------

Even with "filter='data'", *tarfile* is not suited for extracting
untrusted files without prior inspection. Among other issues, the pre-
defined filters do not prevent denial-of-service attacks. Users should
do additional checks.

Here is an incomplete list of things to consider:

* Extract to a "new temporary directory" to prevent e.g. exploiting
  pre-existing links, and to make it easier to clean up after a failed
  extraction.

* Disallow symbolic links if you do not need the functionality.

* When working with untrusted data, use external (e.g. OS-level)
  limits on disk, memory and CPU usage.

* Check filenames against an allow-list of characters (to filter out
  control characters, confusables, foreign path separators, etc.).

* Check that filenames have expected extensions (discouraging files
  that execute when you “click on them”, or extension-less files like
  Windows special device names).

* Limit the number of extracted files, total size of extracted data,
  filename length (including symlink length), and size of individual
  files.

* Check for files that would be shadowed on case-insensitive
  filesystems.

Also note that:

* Tar files may contain multiple versions of the same file. Later ones
  are expected to overwrite any earlier ones. This feature is crucial
  to allow updating tape archives, but can be abused maliciously.

* *tarfile* does not protect against issues with “live” data, e.g. an
  attacker tinkering with the destination (or source) directory while
  extraction (or archiving) is in progress.


Supporting older Python versions
--------------------------------

Extraction filters were added to Python 3.12, and are backported to
older versions as security updates. To check whether the feature is
available, use e.g. "hasattr(tarfile, 'data_filter')" rather than
checking the Python version.

The following examples show how to support Python versions with and
without the feature. Note that setting "extraction_filter" will affect
any subsequent operations.

* Fully trusted archive:

     my_tarfile.extraction_filter = (lambda member, path: member)
     my_tarfile.extractall()

* Use the "'data'" filter if available, but revert to Python 3.11
  behavior ("'fully_trusted'") if this feature is not available:

     my_tarfile.extraction_filter = getattr(tarfile, 'data_filter',
                                            (lambda member, path: member))
     my_tarfile.extractall()

* Use the "'data'" filter; *fail* if it is not available:

     my_tarfile.extractall(filter=tarfile.data_filter)

  or:

     my_tarfile.extraction_filter = tarfile.data_filter
     my_tarfile.extractall()

* Use the "'data'" filter; *warn* if it is not available:

     if hasattr(tarfile, 'data_filter'):
         my_tarfile.extractall(filter='data')
     else:
         # remove this when no longer needed
         warn_the_user('Extracting may be unsafe; consider updating Python')
         my_tarfile.extractall()


Stateful extraction filter example
----------------------------------

While *tarfile*'s extraction methods take a simple *filter* callable,
custom filters may be more complex objects with an internal state. It
may be useful to write these as context managers, to be used like
this:

   with StatefulFilter() as filter_func:
       tar.extractall(path, filter=filter_func)

Such a filter can be written as, for example:

   class StatefulFilter:
       def __init__(self):
           self.file_count = 0

       def __enter__(self):
           return self

       def __call__(self, member, path):
           self.file_count += 1
           return member

       def __exit__(self, *exc_info):
           print(f'{self.file_count} files extracted')


コマンドラインインターフェイス
==============================

バージョン 3.4 で追加.

"tarfile" モジュールは、 tar アーカイブを操作するための簡単なコマンド
ラインインターフェースを提供しています。

tar アーカイブを新規に作成したい場合、"-c" オプションの後にまとめたい
ファイル名のリストを指定してください:

   $ python -m tarfile -c monty.tar  spam.txt eggs.txt

ディレクトリを渡すこともできます:

   $ python -m tarfile -c monty.tar life-of-brian_1979/

tar アーカイブをカレントディレクトリに展開したい場合、"-e" オプション
を使用してください:

   $ python -m tarfile -e monty.tar

ディレクトリ名を渡すことで tar アーカイブを別のディレクトリに取り出す
こともできます:

   $ python -m tarfile -e monty.tar  other-dir/

tar アーカイブ内のファイル一覧を表示するには "-l" を使用してください:

   $ python -m tarfile -l monty.tar


コマンドラインオプション
------------------------

-l <tarfile>
--list <tarfile>

   tarfile 内のファイル一覧を表示します。

-c <tarfile> <source1> ... <sourceN>
--create <tarfile> <source1> ... <sourceN>

   ソースファイルから tarfile を作成します。

-e <tarfile> [<output_dir>]
--extract <tarfile> [<output_dir>]

   *output_dir* が指定されていない場合、カレントディレクトリに tarfile
   を展開します。

-t <tarfile>
--test <tarfile>

   tarfile が有効かどうか調べます。

-v, --verbose

   詳細も出力します。

--filter <filtername>

   Specifies the *filter* for "--extract". See Extraction filters for
   details. Only string names are accepted (that is, "fully_trusted",
   "tar", and "data").

   バージョン 3.9.17 で追加.


使用例
======

tar アーカイブから現在のディレクトリにすべて抽出する方法:

   import tarfile
   tar = tarfile.open("sample.tar.gz")
   tar.extractall()
   tar.close()

tar アーカイブの一部を、リストの代わりにジェネレーター関数を利用して
"TarFile.extractall()" で展開する方法:

   import os
   import tarfile

   def py_files(members):
       for tarinfo in members:
           if os.path.splitext(tarinfo.name)[1] == ".py":
               yield tarinfo

   tar = tarfile.open("sample.tar.gz")
   tar.extractall(members=py_files(tar))
   tar.close()

非圧縮 tar アーカイブをファイル名のリストから作成する方法:

   import tarfile
   tar = tarfile.open("sample.tar", "w")
   for name in ["foo", "bar", "quux"]:
       tar.add(name)
   tar.close()

"with" 文を利用した同じ例:

   import tarfile
   with tarfile.open("sample.tar", "w") as tar:
       for name in ["foo", "bar", "quux"]:
           tar.add(name)

gzip 圧縮 tar アーカイブを作成してメンバー情報のいくつかを表示する方法
:

   import tarfile
   tar = tarfile.open("sample.tar.gz", "r:gz")
   for tarinfo in tar:
       print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
       if tarinfo.isreg():
           print("a regular file.")
       elif tarinfo.isdir():
           print("a directory.")
       else:
           print("something else.")
   tar.close()

"TarFile.add()" 関数の *filter* 引数を利用してユーザー情報をリセットし
ながらアーカイブを作成する方法:

   import tarfile
   def reset(tarinfo):
       tarinfo.uid = tarinfo.gid = 0
       tarinfo.uname = tarinfo.gname = "root"
       return tarinfo
   tar = tarfile.open("sample.tar.gz", "w:gz")
   tar.add("foo", filter=reset)
   tar.close()


サポートしている tar フォーマット
=================================

"tarfile" モジュールは 3 種類の tar フォーマットを作成することができま
す:

* POSIX.1-1988 ustar format ("USTAR_FORMAT"). ファイル名の長さは256文
  字までで、リンク名の長さは100文字までです。最大のファイルサイズは
  8GiBです。このフォーマットは古くて制限が多いですが、広くサポートされ
  ています。

* GNU tar format ("GNU_FORMAT"). 長いファイル名とリンク名、8GiBを超え
  るファイルやスパース(sparse)ファイルをサポートしています。これは
  GNU/Linux システムにおいてデファクト・スタンダードになっています。
  "tarfile" モジュールは長いファイル名を完全にサポートしています。 ス
  パースファイルは読み込みのみサポートしています。

* The POSIX.1-2001 pax format ("PAX_FORMAT"). It is the most flexible
  format with virtually no limits. It supports long filenames and
  linknames, large files and stores pathnames in a portable way.
  Modern tar implementations, including GNU tar, bsdtar/libarchive and
  star, fully support extended *pax* features; some old or
  unmaintained libraries may not, but should treat *pax* archives as
  if they were in the universally-supported *ustar* format. It is the
  current default format for new archives.

  It extends the existing *ustar* format with extra headers for
  information that cannot be stored otherwise. There are two flavours
  of pax headers: Extended headers only affect the subsequent file
  header, global headers are valid for the complete archive and affect
  all following files. All the data in a pax header is encoded in
  *UTF-8* for portability reasons.

他にも、読み込みのみサポートしている tar フォーマットがいくつかありま
す:

* ancient V7 フォーマット。これは Unix 7th Edition から存在する、最初
  の tar フォーマットです。通常のファイルとディレクトリのみ保存します
  。名前は 100 文字を超えてはならず、ユーザー/グループ名に関する情報は
  保存されません。いくつかのアーカイブは、フィールドが ASCII でない文
  字を含む場合に、ヘッダーのチェックサムの計算を誤ります。

* SunOS tar 拡張フォーマット。POSIX.1-2001 pax フォーマットの亜流です
  が、互換性がありません。


Unicode に関する問題
====================

tar フォーマットは、もともとテープドライブにファイルシステムのバックア
ップをとる目的で設計されました。現在、tarアーカイブはファイルを配布す
る際に一般的に用いられ、ネットワーク上で交換されています。オリジナルフ
ォーマットが抱える一つの問題は (他の多くのフォーマットでも同じですが)
、様々な文字エンコーディングのサポートについて考慮していないことです。
例えば、*UTF-8* システム上で作成された通常の tar アーカイブは、非
*ASCII* 文字を含んでいた場合、*Latin-1* システムでは正しく読み取ること
ができません。テキストのメタデータ (ファイル名、リンク名、ユーザー/グ
ループ名など) は破壊されます。残念なことに、アーカイブのエンコーディン
グを自動検出する方法はありません。pax フォーマットはこの問題を解決する
ために設計されました。これは非 ASCII メタデータをユニバーサル文字エン
コーディング *UTF-8* を使用して格納します。

"tarfile" における文字変換処理の詳細は "TarFile" クラスのキーワード引
数 *encoding* および *errors* によって制御されます。

*encoding* はアーカイブのメタデータに使用する文字エンコーディングを指
定します。デフォルト値は "sys.getfilesystemencoding()" で、フォールバ
ックとして "'ascii'" が使用されます。アーカイブの読み書き時に、メタデ
ータはそれぞれデコードまたはエンコードしなければなりません。*encoding*
に適切な値が設定されていない場合、その変換は失敗することがあります。

引数 *errors* は文字を変換できない時の扱いを指定します。指定できる値は
エラーハンドラ 節を参照してください。デフォルトのスキームは
"'surrogateescape'" で、Python はそのファイルシステムの呼び出しも使用
します。ファイル名、コマンドライン引数、および環境変数 を参照してくだ
さい。

デフォルトの "PAX_FORMAT" アーカイブでは、メタデータはすべて *UTF-8*
で格納されるため、*encoding* は通常指定する必要はありません。
*encoding* は、まれにある、バイナリの pax ヘッダーがデコードされた場合
、あるいはサロゲート文字を含む文字列が格納されていた場合に使用されます
。
