tarfile --- tar アヌカむブファむルの読み曞き¶

゜ヌスコヌド: Lib/tarfile.py


The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write .zip files, or the higher-level functions in shutil.

いく぀かの事実ず圢態:

  • モゞュヌルが利甚可胜な堎合、gzip、bz2、compression.zstd ならびに lzma で圧瞮されたアヌカむブを読み曞きしたす。

    If any of these optional modules are missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see オプションのモゞュヌルの芁件.

  • POSIX.1-1988 (ustar) フォヌマットの読み曞きをサポヌトしおいたす。

  • longname および longlink 拡匵を含む GNU tar フォヌマットの読み曞きをサポヌトしおいたす。スパヌスファむルの埩元を含む sparse 拡匵は読み蟌みのみサポヌトしおいたす。

  • POSIX.1-2001 (pax) フォヌマットの読み曞きをサポヌトしおいたす。

  • ディレクトリ、䞀般ファむル、ハヌドリンク、シンボリックリンク、fifo、キャラクタヌデバむスおよびブロックデバむスを凊理したす。たた、タむムスタンプ、アクセス蚱可や所有者のようなファむル情報の取埗および保存が可胜です。

バヌゞョン 3.3 で倉曎: lzma 圧瞮をサポヌトしたした。

バヌゞョン 3.12 で倉曎: Archives are extracted using a filter, which makes it possible to either limit surprising/dangerous features, or to acknowledge that they are expected and the archive is fully trusted.

バヌゞョン 3.14 で倉曎: Set the default extraction filter to data, which disallows some dangerous features such as links to absolute paths or paths outside of the destination. Previously, the filter strategy was equivalent to fully_trusted.

バヌゞョン 3.14 で倉曎: Added support for Zstandard compression using compression.zstd.

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 圧瞮で読み蟌み甚にオヌプンしたす。

'r:zst'

Zstandard 圧瞮で読み蟌み甚にオヌプンしたす。

'x' or 'x:'

圧瞮せずに tarfile を排他的に䜜成したす。tarfile が既存の堎合 FileExistsError 䟋倖を送出したす。

'x:gz'

gzip 圧瞮で tarfile を䜜成したす。tarfile が既存の堎合 FileExistsError 䟋倖を送出したす。

'x:bz2'

bzip2 圧瞮で tarfile を䜜成したす。tarfile が既存の堎合 FileExistsError 䟋倖を送出したす。

'x:xz'

lzma 圧瞮で tarfile を䜜成したす。tarfile が既存の堎合 FileExistsError 䟋倖を送出したす。

'x:zst'

Zstandard 圧瞮で tarfile を䜜成したす。tarfile が既存の堎合 FileExistsError 䟋倖を送出したす。

'a' たたは 'a:'

非圧瞮で远蚘甚にオヌプンしたす。ファむルが存圚しない堎合は新たに䜜成されたす。

'w' たたは 'w:'

非圧瞮で曞き蟌み甚にオヌプンしたす。

'w:gz'

gzip 圧瞮で曞き蟌み甚にオヌプンしたす。

'w:bz2'

bzip2 圧瞮で曞き蟌み甚にオヌプンしたす。

'w:xz'

lzma 圧瞮で曞き蟌み甚にオヌプンしたす。

'w:zst'

Zstandard 圧瞮で曞き蟌み甚にオヌプンしたす。

'a:gz'、'a:bz2'、'a:xz' は利甚できないこずに泚意しお䞋さい。もし mode が、ある (圧瞮した) ファむルを読み蟌み甚にオヌプンするのに適しおいないなら、ReadError が送出されたす。これを防ぐには mode 'r' を䜿っお䞋さい。もし圧瞮方匏がサポヌトされおいなければ、CompressionError が送出されたす。

もし fileobj が指定されおいれば、それは name でバむナリモヌドでオヌプンされた ファむルオブゞェクト の代替ずしお䜿うこずができたす。そのファむルオブゞェクトの䜍眮が 0 であるこずを前提に動䜜したす。

For modes 'w:gz', 'x:gz', 'w|gz', 'w:bz2', 'x:bz2', 'w|bz2', tarfile.open() accepts the keyword argument compresslevel (default 9) to specify the compression level of the file.

'w:xz'、'x:xz' および 'w|xz' モヌドの堎合、tarfile.open() はファむルの圧瞮レベルを指定するキヌワヌド匕数 preset を受け付けたす。

For modes 'w:zst', 'x:zst' and 'w|zst', tarfile.open() accepts the keyword argument level to specify the compression level of the file. The keyword argument options may also be passed, providing advanced Zstandard compression parameters described by CompressionParameter. The keyword argument zstd_dict can be passed to provide a ZstdDict, a Zstandard dictionary used to improve compression of smaller amounts of data.

For special purposes, there is a second format for mode: 'filemode|[compression]'. tarfile.open() will return a TarFile object that processes its data as a stream of blocks. No random seeking will be done on the file. If given, fileobj may be any object that has a read() or write() method (depending on the mode) that works with bytes. bufsize specifies the blocksize and defaults to 20 * 512 bytes. Use this variant in combination with e.g. sys.stdin.buffer, a socket file object or a tape device. However, such a TarFile object is limited in that it does not allow random access, see 䜿甚䟋. The currently possible modes:

モヌド

動䜜

'r|*'

tar ブロックの stream を圧瞮方法に関しお透過的に読み蟌み甚にオヌプンしたす。

'r|'

非圧瞮 tar ブロックの stream を読み蟌み甚にオヌプンしたす。

'r|gz'

gzip 圧瞮の stream を読み蟌み甚にオヌプンしたす。

'r|bz2'

bzip2 圧瞮の stream を読み蟌み甚にオヌプンしたす。

'r|xz'

lzma 圧瞮の stream を読み蟌み甚にオヌプンしたす。

'r|zst'

Zstandard 圧瞮の stream を読み蟌み甚にオヌプンしたす。

'w|'

非圧瞮の stream を曞き蟌み甚にオヌプンしたす。

'w|gz'

gzip 圧瞮の stream を曞き蟌み甚にオヌプンしたす。

'w|bz2'

bzip2 圧瞮の stream を曞き蟌み甚にオヌプンしたす。

'w|xz'

lzma 圧瞮の stream を曞き蟌み甚にオヌプンしたす。

'w|zst'

Zstandard 圧瞮の stream を曞き蟌み甚にオヌプンしたす。

バヌゞョン 3.5 で倉曎: 'x' (排他的䜜成) モヌドが远加されたした。

バヌゞョン 3.6 で倉曎: name パラメタが path-like object を受け付けるようになりたした。

バヌゞョン 3.12 で倉曎: The compresslevel keyword argument also works for streams.

バヌゞョン 3.14 で倉曎: The preset keyword argument also works for streams.

class tarfile.TarFile

tar アヌカむブを読み曞きするためのクラスです。このクラスを盎接䜿わないこず: 代わりに tarfile.open() を䜿っおください。TarFile オブゞェクト を参照しおください。

tarfile.is_tarfile(name)¶

Return True if name is a tar archive file, that the tarfile module can read. name may be a str, file, or file-like object.

バヌゞョン 3.9 で倉曎: ファむルおよびファむルラむクオブゞェクトをサポヌトしたした。

The tarfile module defines the following exceptions:

exception tarfile.TarError¶

Base class for all tarfile exceptions.

exception tarfile.ReadError¶

Is raised when a tar archive is opened, that either cannot be handled by the tarfile module or is somehow invalid.

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__.

Added in version 3.14.

モゞュヌルレベルで以䞋の定数が利甚できたす。

tarfile.ENCODING¶

既定の文字゚ンコヌディング。Windows では 'utf-8' 、それ以倖では sys.getfilesystemencoding() の返り倀です。

tarfile.REGTYPE¶
tarfile.AREGTYPE¶

A regular file type.

tarfile.LNKTYPE¶

A link (inside tarfile) type.

tarfile.SYMTYPE¶

A symbolic link type.

tarfile.CHRTYPE¶

A character special device type.

tarfile.BLKTYPE¶

A block special device type.

tarfile.DIRTYPE¶

A directory type.

tarfile.FIFOTYPE¶

A FIFO special device type.

tarfile.CONTTYPE¶

A contiguous file type.

tarfile.GNUTYPE_LONGNAME¶

A GNU tar longname type.

A GNU tar longlink type.

tarfile.GNUTYPE_SPARSE¶

A GNU tar sparse file type.

Each of the following constants defines a tar archive format that the tarfile module is able to create. See section サポヌトしおいる tar フォヌマット for details.

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 ブロックが終了したずきにオブゞェクトはクロヌズされたす。䟋倖が発生した時、内郚で利甚されおいるファむルオブゞェクトのみがクロヌズされ、曞き蟌み甚にオヌプンされたアヌカむブのファむナラむズは行われないこずに泚意しおください。䜿甚䟋 節のナヌスケヌスを参照しおください。

Added in version 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, stream=False)¶

以䞋のすべおの匕数はオプションで、むンスタンス属性ずしおもアクセスできたす。

name is the pathname of the archive. name may be a path-like object. It can be omitted if fileobj is given. In this case, the file object's name attribute is used if it exists.

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 グロヌバルヘッダヌに远加されたす。

If stream is set to True then while reading the archive info about files in the archive are not cached, saving memory.

バヌゞョン 3.2 で倉曎: 匕数 errors のデフォルトが 'surrogateescape' になりたした。

バヌゞョン 3.5 で倉曎: 'x' (排他的䜜成) モヌドが远加されたした。

バヌゞョン 3.6 で倉曎: name パラメタが path-like object を受け付けるようになりたした。

バヌゞョン 3.13 で倉曎: Add the stream parameter.

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 specifies how members are modified or rejected before extraction. See Extraction filters for details. It is recommended to set this explicitly only if specific tar features are required, or as filter='data' to support Python versions with a less secure default (3.13 and lower).

譊告

Never extract archives from untrusted sources without prior inspection.

Since Python 3.14, the default (data) will prevent the most dangerous security issues. However, it will not prevent all unintended or insecure behavior. Read the Extraction filters section for details.

バヌゞョン 3.5 で倉曎: numeric_owner 匕数が远加されたした。

バヌゞョン 3.6 で倉曎: path パラメタが path-like object を受け付けるようになりたした。

バヌゞョン 3.12 で倉曎: filter パラメヌタが远加されたした。

バヌゞョン 3.14 で倉曎: The filter parameter now defaults to 'data'.

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() メ゜ッドの利甚を考慮するべきです。

譊告

Never extract archives from untrusted sources without prior inspection. See the warning for extractall() for details.

バヌゞョン 3.2 で倉曎: パラメヌタヌに set_attrs を远加したした。

バヌゞョン 3.5 で倉曎: numeric_owner 匕数が远加されたした。

バヌゞョン 3.6 で倉曎: path パラメタが path-like object を受け付けるようになりたした。

バヌゞョン 3.12 で倉曎: filter パラメヌタが远加されたした。

TarFile.extractfile(member)¶

アヌカむブからメンバヌをファむルオブゞェクトずしお抜出したす。 member はファむル名でも TarInfo オブゞェクトでも構いたせん。member が䞀般ファむルたたはリンクの堎合、io.BufferedReader オブゞェクトが返されたす。 存圚するそれ以倖のメンバヌでは、 None が返されたす。 それ以倖の堎合、None が返されたす。 アヌカむブに member が存圚しない堎合は KeyError が送出されたす。

バヌゞョン 3.3 で倉曎: 戻り倀が io.BufferedReader オブゞェクトになりたした。

バヌゞョン 3.13 で倉曎: The returned io.BufferedReader object has the mode attribute which is always equal to 'rb'.

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¶

Added in version 3.12.

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), extraction methods will 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.

バヌゞョン 3.14 で倉曎: The default filter is set to data, which disallows some dangerous features such as links to absolute paths or paths outside of the destination. Previously, the default was equivalent to fully_trusted.

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)¶

Add the TarInfo object tarinfo to the archive. If tarinfo represents a non zero-size regular file, the fileobj argument should be a binary file, and tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects directly, or by using gettarinfo().

バヌゞョン 3.13 で倉曎: fileobj must be given for non-zero-sized regular files.

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

os.stat() の結果か、既存のファむルに盞圓するものから、TarInfo オブゞェクトを䜜成したす。このファむルは、name で名付けられるか、ファむル蚘述子を持぀ file object fileobj ずしお指定されたす。name は 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: dict¶

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:

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.12 で倉曎: 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.12 で倉曎: 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.12 で倉曎: Can be set to None for extract() and extractall(), causing extraction to skip applying this attribute.

TarInfo.gid: int¶

ファむルメンバヌを保存した元のナヌザヌのグルヌプ ID。

バヌゞョン 3.12 で倉曎: Can be set to None for extract() and extractall(), causing extraction to skip applying this attribute.

TarInfo.uname: str¶

ファむルメンバヌを保存した元のナヌザヌのナヌザヌ名。

バヌゞョン 3.12 で倉曎: Can be set to None for extract() and extractall(), causing extraction to skip applying this attribute.

TarInfo.gname: str¶

ファむルメンバヌを保存した元のナヌザヌのグルヌプ名。

バヌゞョン 3.12 で倉曎: Can be set to None for extract() and extractall(), causing extraction to skip applying this attribute.

TarInfo.chksum: int¶

Header checksum.

TarInfo.devmajor: int¶

Device major number.

TarInfo.devminor: int¶

Device minor number.

TarInfo.offset: int¶

The tar header starts here.

TarInfo.offset_data: int¶

The file's data starts here.

TarInfo.sparse¶

Sparse member information.

TarInfo.pax_headers: dict¶

pax 拡匵ヘッダヌに関連付けられた、key-value ペアの蟞曞。

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

Added in version 3.12.

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()¶

Return True if the TarInfo object is a regular file.

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¶

Added in version 3.12.

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.

譊告

None of the available filters blocks all dangerous archive features. Never extract archives from untrusted sources without prior inspection. See also Hints for further verification.

参考

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 'data' filter will be used.

    バヌゞョン 3.14 で倉曎: The default filter is set to data. Previously, the default was equivalent to fully_trusted.

  • 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.

  • Normalize filenames (TarInfo.name) that contain .. components using os.path.normpath(). Note that this removes internal .. components, which may change the meaning of the name if it traverses symbolic links.

  • 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_IWGRP | S_IWOTH).

Return the modified TarInfo member.

バヌゞョン 3.14.8 で倉曎: Filenames containing .. components are now normalized.

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_IRUSR | S_IWUSR).

    • Remove the group & other executable permission (S_IXGRP | 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.

Note that this filter does not block all dangerous archive features. See Hints for further verification for details.

バヌゞョン 3.14 で倉曎: 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, and so on).

  • 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, but may be 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)
    

    もしくは:

    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')

コマンドラむンむンタヌフェむス¶

Added in version 3.4.

The tarfile module provides a simple command-line interface to interact with tar archives.

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).

䜿甚䟋¶

Reading examples¶

tar アヌカむブから珟圚のディレクトリにすべお抜出する方法:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall(filter='data')
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()

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()

Writing examples¶

非圧瞮 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)

How to create and write an archive to stdout using sys.stdout.buffer in the fileobj parameter in TarFile.add():

import sys
import tarfile
with tarfile.open("sample.tar.gz", "w|gz", fileobj=sys.stdout.buffer) as tar:
    for name in ["foo", "bar", "quux"]:
        tar.add(name)

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 フォヌマット¶

There are three tar formats that can be created with the tarfile module:

  • POSIX.1-1988 ustar format (USTAR_FORMAT). ファむル名の長さは256文字たでで、リンク名の長さは100文字たでです。最倧のファむルサむズは8GiBです。このフォヌマットは叀くお制限が倚いですが、広くサポヌトされおいたす。

  • The GNU tar format (GNU_FORMAT). It supports long filenames and linknames, files bigger than 8 GiB and sparse files. It is the de facto standard on GNU/Linux systems. tarfile fully supports the GNU tar extensions for long names, sparse file support is read-only.

  • 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 を䜿甚しお栌玍したす。

The details of character conversion in tarfile are controlled by the encoding and errors keyword arguments of the TarFile class.

encoding はアヌカむブのメタデヌタに䜿甚する文字゚ンコヌディングを指定したす。デフォルト倀は sys.getfilesystemencoding() で、フォヌルバックずしお 'ascii' が䜿甚されたす。アヌカむブの読み曞き時に、メタデヌタはそれぞれデコヌドたたぱンコヌドしなければなりたせん。encoding に適切な倀が蚭定されおいない堎合、その倉換は倱敗するこずがありたす。

匕数 errors は文字を倉換できない時の扱いを指定したす。指定できる倀は ゚ラヌハンドラ 節を参照しおください。デフォルトのスキヌムは 'surrogateescape' で、Python はそのファむルシステムの呌び出しも䜿甚したす。ファむル名、コマンドラむン匕数、および環境倉数 を参照しおください。

デフォルトの PAX_FORMAT アヌカむブでは、メタデヌタはすべお UTF-8 で栌玍されるため、encoding は通垞指定する必芁はありたせん。encoding は、たれにある、バむナリの pax ヘッダヌがデコヌドされた堎合、あるいはサロゲヌト文字を含む文字列が栌玍されおいた堎合に䜿甚されたす。