-
命令行选项
-
受支持的 tar 格式
-
Unicode 问题
源代码:
Lib/tarfile.py
tarfile
模块可以用来读写 tar 归档,包括使用 gzip, bz2 和 lzma 压缩的归档。 请使用
zipfile
模块来读写
.zip
文件,或者使用
shutil
的高层级函数。
一些事实和数字:
-
读写
gzip
,
bz2
和
lzma
解压的归档要求相应的模块可用。
-
支持读取 / 写入 POSIX.1-1988 (ustar) 格式。
-
对 GNU tar 格式的读/写支持,包括
longname
和
longlink
扩展,对所有种类
sparse
扩展的只读支持,包括 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'
。 以下是模式组合的完整列表:
请注意
'a:gz'
,
'a:bz2'
或
'a:xz'
是不可能的组合。 如果
mode
不适用于打开特定(压缩的)文件用于读取,则会引发
ReadError
。 请使用
mode
'r'
来避免这种情况。 如果某种压缩方法不受支持,则会引发
CompressionError
。
如果指定了
fileobj
,它会被用作对应于
name
的以二进制模式打开的
file object
的替代。 它会被设定为处在位置 0。
对于
'w:gz'
,
'r:gz'
,
'w:bz2'
,
'r:bz2'
,
'x:gz'
,
'x:bz2'
等模式,
tarfile.open()
接受关键字参数
compresslevel
(默认值为
9
) 来指定文件的压缩等级。
针对特殊的目的,还存在第二种
mode
格式:
'filemode|[compression]'
。
tarfile.open()
将返回一个将其数据作为数据块流来处理的
TarFile
对象。 对此文件将不能执行随机查找。 如果给定了
fileobj
,它可以是任何具有
read()
或
write()
方法 (由
mode
确定) 的对象。
bufsize
指定块大小,默认值为
20
*
512
字节。 可与此格式组合使用的有
sys.stdin
, 套接字
file object
或磁带设备等。 但是,对于这样的
TarFile
对象存在不允许随机访问的限制,参见
例子
。 目前可用的模式如下:
exception
tarfile.
LinkOutsideDestinationError
-
Raised to refuse extracting a symbolic link pointing outside the destination
directory.
以下常量在模块层级上可用:
tarfile.
ENCODING
-
默认的字符编码格式:在 Windows 上为
'utf-8'
,其他系统上则为
sys.getfilesystemencoding()
所返回的值。
以下常量各自定义了一个
tarfile
模块能够创建的 tar 归档格式。 相关细节请参阅
受支持的 tar 格式
小节。
tarfile.
USTAR_FORMAT
-
POSIX.1-1988 (ustar) 格式。
TarFile 对象
TarFile
对象提供了一个 tar 归档的接口。 一个 tar 归档就是数据块的序列。 一个归档成员(被保存文件)是由一个标头块加多个数据块组成的。 一个文件可以在一个 tar 归档中多次被保存。 每个归档成员都由一个
TarInfo
对象来代表,详情参见
TarInfo 对象
。
TarFile
对象可在
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
中的一个。 当读取时,格式将被自动检测,即使单个归档中存在不同的格式。
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 版更改:
使用
'surrogateescape'
作为
errors
参数的默认值。
在 3.5 版更改:
添加了
'x'
(单独创建) 模式。
在 3.6 版更改:
name
形参接受一个
path-like object
。
TarFile.
list
(
verbose=True
,
*
,
members=None
)
-
将内容清单打印到
sys.stdout
。 如果
verbose
为
False
,则将只打印成员名称。 如果为
True
,则输出将类似于
ls -l
的输出效果。 如果给定了可选的
members
,它必须为
getmembers()
所返回的列表的一个子集。
在 3.5 版更改:
添加了
members
形参。
TarFile.
extractall
(
path="."
,
members=None
,
*
,
numeric_owner=False
,
filter=None
)
-
将归档中的所有成员提取到当前工作目录或
path
目录。 如果给定了可选的
members
,则它必须为
getmembers()
所返回的列表的一个子集。 字典信息例如所有者、修改时间和权限会在所有成员提取完毕后被设置。 这样做是为了避免两个问题:目录的修改时间会在每当在其中创建文件时被重置。 并且如果目录的权限不允许写入,提取文件到目录的操作将失败。
如果
numeric_owner
为
True
,则将使用来自 tarfile 的 uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下,则会使用来自 tarfile 的名称值。
The
filter
argument, which was added in Python 3.8.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.
绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有可能在
path
之外创建文件,例如某些成员具有以
"/"
开始的绝对路径文件名或带有两个点号
".."
的文件名。
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.8.17 版更改:
添加了
filter
形参。
TarFile.
extract
(
member
,
path=""
,
set_attrs=True
,
*
,
numeric_owner=False
,
filter=None
)
-
从归档中提取出一个成员放入当前工作目录,将使用其完整名称。 成员的文件信息会尽可能精确地被提取。
member
可以是一个文件名或
TarInfo
对象。 你可以使用
path
指定一个不同的目录。
path
可以是一个
path-like object
。 将会设置文件属性 (owner, mtime, mode) 除非
set_attrs
为假值。
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.8.17 版更改:
添加了
filter
形参。
TarFile.
extractfile
(
member
)
-
将归档中的一个成员提取为文件对象。
member
可以是一个文件名或
TarInfo
对象。 如果
member
是一个常规文件或链接,则会返回一个
io.BufferedReader
对象。 在其他情况下将返回
None
。
在 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.
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.
gettarinfo
(
name=None
,
arcname=None
,
fileobj=None
)
-
基于
os.stat()
的结果或者现有文件的相同数据创建一个
TarInfo
。 文件或者是命名为
name
,或者是使用文件描述符指定为一个
file object
fileobj
。
name
可以是一个
path-like object
。 如果给定了
arcname
,则它将为归档中的文件指定一个替代名称,在其他情况下,名称将从
fileobj
的
name
属性或
name
参数获取。 名称应当是一个文本字符串。
你可以在使用
addfile()
添加
TarInfo
的某些属性之前修改它们。 如果文件对象不是从文件开头进行定位的普通文件对象,
size
之类的属性就可能需要修改。 例如
GzipFile
之类的文件就属于这种情况。
name
也可以被修改,在这种情况下
arcname
可以是一个占位字符串。
在 3.6 版更改:
name
形参接受一个
path-like object
。
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.8.17 版更改:
Added
replace()
and handling of
None
.
class
tarfile.
TarInfo
(
name=""
)
-
创建一个
TarInfo
对象。
classmethod
TarInfo.
frombuf
(
buf
,
encoding
,
errors
)
-
基于字符串缓冲区
buf
创建并返回一个
TarInfo
对象。
如果缓冲区无效则会引发
HeaderError
。
TarInfo.
tobuf
(
format=DEFAULT_FORMAT
,
encoding=ENCODING
,
errors='surrogateescape'
)
-
基于
TarInfo
对象创建一个字符串缓冲区。 有关参数的信息请参见
TarFile
类的构造器。
在 3.2 版更改:
使用
'surrogateescape'
作为
errors
参数的默认值。
TarInfo
对象具有以下公有数据属性:
TarInfo.
name
: str
-
归档成员的名称。
TarInfo.
mtime
: int | float
-
Time of last modification in seconds since the
epoch
,
as in
os.stat_result.st_mtime
.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
在 3.8.17 版更改:
Can be set to
None
for
extract()
and
extractall()
, causing extraction to skip applying this
attribute.
TarInfo.replace(name=..., mtime=..., mode=..., linkname=...,
uid=..., gid=..., uname=..., gname=...,
deep=True)
3.8.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
。
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.
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:
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.