tarfile — tar 아카이브 파일 읽기와 쓰기

소스 코드: Lib/tarfile.py


tarfile 모듈을 사용하면 gzip, bz2 및 lzma 압축을 사용하는 것을 포함하여, tar 아카이브를 읽고 쓸 수 있습니다. .zip 파일을 읽거나 쓰려면 zipfile 모듈이나 shutil에 있는 고수준 함수를 사용하십시오.

몇 가지 세부 사항:

  • 해당 모듈을 사용할 수 있으면 gzip, bz2lzma 압축 아카이브를 읽고 씁니다.

  • POSIX.1-1988 (ustar) 형식에 대한 읽기/쓰기 지원.

  • longnamelonglink 확장을 포함한 GNU tar 형식에 대한 읽기/쓰기 지원, 스파스(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'입니다. 다음은 mode 조합의 전체 목록입니다:

모드

동작

'r' 또는 'r:*'

투명한 압축으로 읽기 위해 엽니다 (권장합니다).

'r:'

압축하지 않고 독점적으로 읽기 위해 엽니다.

'r:gz'

gzip 압축으로 읽기 위해 엽니다.

'r:bz2'

bzip2 압축으로 읽기 위해 엽니다.

'r:xz'

lzma 압축으로 읽기 위해 엽니다.

'x' 또는 'x:'

압축하지 않고 독점적으로 tar 파일을 만듭니다. 이미 있으면 FileExistsError 예외를 발생시킵니다.

'x:gz'

gzip 압축으로 tar 파일을 만듭니다. 이미 있으면 FileExistsError 예외를 발생시킵니다.

'x:bz2'

bzip2 압축으로 tar 파일을 만듭니다. 이미 있으면 FileExistsError 예외를 발생시킵니다.

'x:xz'

lzma 압축으로 tar 파일을 만듭니다. 이미 있으면 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)을 받아들입니다.

For modes 'w:xz' and 'x:xz', tarfile.open() accepts the keyword argument preset to specify the compression level of the file.

특별한 목적으로, mode에는 두 번째 형식이 있습니다: 'filemode|[compression]'. tarfile.open()은 데이터를 블록 스트림으로 처리하는 TarFile 객체를 반환합니다. 파일에서 무작위 탐색(random seeking)을 수행하지 않습니다. 주어지면,, fileobj는 (mode에 따라) read()write() 메서드가 있는 임의의 객체일 수 있습니다. bufsize는 블록 크기를 지정하고 기본값은 20 * 512 바이트입니다. 이 변형을 예를 들어 sys.stdin, 소켓 파일 객체 또는 테이프 장치와 함께 사용하십시오. 그러나, 이러한 TarFile 객체는 무작위 액세스를 허용하지 않는다는 제한이 있습니다 (를 참조하십시오). 현재 가능한 모드는 다음과 같습니다:

모드

동작

'r|*'

투명한 압축으로 읽기 위해 tar 블록의 스트림을 엽니다.

'r|'

읽기 위해 압축되지 않은 tar 블록의 스트림을 엽니다.

'r|gz'

읽기 위해 gzip 압축 스트림을 엽니다.

'r|bz2'

읽기 위해 bzip2 압축 스트림을 엽니다.

'r|xz'

읽기 위해 lzma 압축 스트림을 엽니다.

'w|'

쓰기 위해 압축되지 않은 스트림을 엽니다.

'w|gz'

쓰기 위해 gzip 압축 스트림을 엽니다.

'w|bz2'

쓰기 위해 bzip2 압축 스트림을 엽니다.

'w|xz'

쓰기 위해 lzma 압축 스트림을 엽니다.

버전 3.5에서 변경: 'x' (독점 생성) 모드가 추가되었습니다.

버전 3.6에서 변경: name 매개 변수는 경로류 객체를 받아들입니다.

class tarfile.TarFile

tar 아카이브를 읽고 쓰는 클래스. 이 클래스를 직접 사용하지 마십시오: 대신 tarfile.open()을 사용하십시오. TarFile 객체를 참조하십시오.

tarfile.is_tarfile(name)

nametarfile 모듈이 읽을 수 있는 tar 아카이브 파일이면 True를 반환합니다. namestr, 파일 또는 파일류 객체일 수 있습니다.

버전 3.9에서 변경: 파일과 파일류 객체 지원.

tarfile 모듈은 다음 예외를 정의합니다:

exception tarfile.TarError

모든 tarfile 예외의 베이스 클래스.

exception tarfile.ReadError

tarfile 모듈에서 처리할 수 없거나 어떤 식으로든 유효하지 않은 tar 아카이브가 열릴 때 발생합니다.

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.

모듈 수준에서 다음 상수를 사용할 수 있습니다:

tarfile.ENCODING

기본 문자 인코딩: 윈도우의 경우 '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 문에서 컨텍스트 관리자로 사용될 수 있습니다. 블록이 완료되면 자동으로 닫힙니다. 예외가 있는 경우, 쓰기 위해 열린 아카이브는 마무리되지 않음에 유의하십시오; 내부적으로 사용된 파일 객체만 닫힙니다. 사용 사례는 섹션을 참조하십시오.

버전 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경로류 객체일 수 있습니다. fileobj가 주어지면 생략할 수 있습니다. 이 경우, 파일 객체의 name 어트리뷰트가 있다면 사용됩니다.

mode는 기존 아카이브에서 읽는 'r', 기존 파일에 데이터를 추가하는 'a', 기존 파일을 덮어쓰는 새 파일을 만드는 'w' 또는 존재하지 않을 때만 새 파일을 만드는 'x'입니다.

fileobj가 주어지면, 데이터를 읽거나 쓰는 데 사용됩니다. 그것이 결정될 수 있다면, modefileobj의 모드에 의해 재정의됩니다. fileobj는 위치 0에서 사용됩니다.

참고

TarFile이 닫힐 때, fileobj는 닫히지 않습니다.

format은 쓰기를 위한 아카이브 형식을 제어합니다. 모듈 수준에서 정의되는 상수 USTAR_FORMAT, GNU_FORMAT 또는 PAX_FORMAT 중 하나여야 합니다. 읽을 때, 형식은 자동 감지됩니다, 단일 아카이브에 다른 형식이 존재할 때조차 그렇습니다.

tarinfo 인자를 사용하여 기본 TarInfo 클래스를 다른 클래스로 바꿀 수 있습니다.

dereferenceFalse이면, 아카이브에 심볼릭과 하드 링크를 추가합니다. True이면, 대상 파일의 내용을 아카이브에 추가합니다. 이는 심볼릭 링크를 지원하지 않는 시스템에는 영향을 미치지 않습니다.

ignore_zerosFalse이면, 빈 블록을 아카이브의 끝으로 처리합니다. True이면, 비어있는 (그래서 잘못된) 블록을 건너뛰고 최대한 많은 멤버를 확보하려고 합니다. 이어붙였거나 손상된 아카이브를 읽을 때만 유용합니다.

debug0(디버그 메시지 없음)에서 3(모든 디버그 메시지)까지 설정할 수 있습니다. 메시지는 sys.stderr에 기록됩니다.

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

encodingerrors 인자는 아카이브를 읽거나 쓰는 데 사용되는 문자 인코딩과 변환 에러 처리 방법을 정의합니다. 기본 설정은 대부분의 사용자에게 적용됩니다. 자세한 정보는 유니코드 문제 섹션을 참조하십시오.

pax_headers 인자는 선택적인 문자열의 딕셔너리로, formatPAX_FORMAT이면 pax 전역 헤더로 추가됩니다.

버전 3.2에서 변경: errors 인자의 기본값으로 'surrogateescape'를 사용합니다.

버전 3.5에서 변경: 'x' (독점 생성) 모드가 추가되었습니다.

버전 3.6에서 변경: name 매개 변수는 경로류 객체를 받아들입니다.

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으로 인쇄합니다. verboseFalse이면, 멤버 이름만 인쇄됩니다. True이면, ls -l과 유사한 출력이 생성됩니다. 선택적 members가 제공되면, getmembers()가 반환한 리스트의 부분집합이어야 합니다.

버전 3.5에서 변경: members 매개 변수를 추가했습니다.

TarFile.next()

TarFile을 읽기 위해 열었을 때, 아카이브의 다음 멤버를 TarInfo 객체로 반환합니다. 더는 없으면, None을 반환합니다.

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

아카이브의 모든 멤버(members)를 현재 작업 디렉터리나 디렉터리 path로 추출합니다. 선택적 members가 제공되면, getmembers()가 반환하는 리스트의 부분집합이어야 합니다. 소유자, 수정 시간 및 권한과 같은 디렉터리 정보는 모든 멤버가 추출된 후에 설정됩니다. 이것은 두 가지 문제를 해결하기 위한 것입니다: 디렉터리의 수정 시간은 파일이 생성될 때마다 재설정됩니다. 또한 디렉터리의 권한이 쓰기를 허용하지 않으면, 파일 추출이 실패합니다.

numeric_ownerTrue이면, tar 파일의 uid와 gid 번호는 추출된 파일의 소유자/그룹을 설정하는 데 사용됩니다. 그렇지 않으면, tar 파일의 이름값이 사용됩니다.

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.

경고

사전 검사 없이 신뢰할 수 없는 출처에서 온 아카이브를 추출하지 마십시오. 파일이 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 매개 변수는 경로류 객체를 받아들입니다.

버전 3.9.17에서 변경: filter 매개 변수를 추가했습니다.

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

전체 이름을 사용하여, 아카이브에서 현재 작업 디렉터리로 멤버(member)를 추출합니다. 파일 정보는 최대한 정확하게 추출됩니다. member는 파일명이나 TarInfo 객체일 수 있습니다. path를 사용하여 다른 디렉터리를 지정할 수 있습니다. path경로류 객체일 수 있습니다. 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 매개 변수는 경로류 객체를 받아들입니다.

버전 3.9.17에서 변경: filter 매개 변수를 추가했습니다.

TarFile.extractfile(member)

아카이브에서 멤버(member)를 파일 객체로 추출합니다. member는 파일명이나 TarInfo 객체일 수 있습니다. member가 일반 파일이나 링크이면, io.BufferedReader 객체가 반환됩니다. 다른 모든 기존 멤버에 대해서는, 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은 아카이브에 있는 파일의 대체 이름을 지정합니다. 디렉터리는 기본적으로 재귀적으로 추가됩니다. recursiveFalse로 설정하면, 이를 피할 수 있습니다. 재귀는 항목을 정렬된 순서로 추가합니다. filter가 제공되면, TarInfo 객체 인자를 취하고 변경된 TarInfo 객체를 반환하는 함수여야 합니다. 이것이 대신 None을 반환하면, TarInfo 객체가 아카이브에서 제외됩니다. 예는 를 참조하십시오.

버전 3.2에서 변경: filter 매개 변수를 추가했습니다.

버전 3.7에서 변경: 재귀는 항목을 정렬된 순서로 추가합니다.

TarFile.addfile(tarinfo, fileobj=None)

TarInfo 객체 tarinfo를 아카이브에 추가합니다. fileobj가 제공되면, 바이너리 파일이어야 하고, 여기서 tarinfo.size 바이트를 읽어서 아카이브에 추가합니다. TarInfo 객체를 직접 혹은 gettarinfo()를 사용하여 만들 수 있습니다.

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

기존 파일에서 os.stat()이나 이와 동등한 것의 결과로부터 TarInfo 객체를 만듭니다. 파일은 name으로 이름을 지정하거나, 파일 기술자를 갖는 파일 객체 fileobj로 지정됩니다. name경로류 객체일 수 있습니다. 주어지면, arcname은 아카이브에 있는 파일의 대체 이름을 지정하고, 그렇지 않으면, 이름은 fileobjname 어트리뷰트나 name 인자에서 취합니다. 이름은 텍스트 문자열이어야 합니다.

addfile()을 사용하여 추가하기 전에 TarInfo의 일부 어트리뷰트를 수정할 수 있습니다. 파일 객체가 파일의 시작 부분에 위치한 일반 파일 객체가 아니면, size와 같은 어트리뷰트를 수정해야 할 수 있습니다. GzipFile과 같은 객체가 이 상황에 해당합니다. name도 수정될 수 있으며, 이 경우 arcname은 더미 문자열일 수 있습니다.

버전 3.6에서 변경: name 매개 변수는 경로류 객체를 받아들입니다.

TarFile.close()

TarFile을 닫습니다. 쓰기 모드에서는, 두 개의 마무리 0블록이 아카이브에 추가됩니다.

TarFile.pax_headers

pax 전역 헤더의 키-값 쌍을 포함하는 딕셔너리.

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:

버전 3.9.17에서 변경: Added replace() and handling of None.

class tarfile.TarInfo(name="")

TarInfo 객체를 만듭니다.

classmethod TarInfo.frombuf(buf, encoding, errors)

문자열 버퍼 buf에서 TarInfo 객체를 만들고 반환합니다.

버퍼가 유효하지 않으면 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

대상 파일 이름의 이름, LNKTYPESYMTYPE 유형의 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 확장 헤더의 키-값 쌍을 포함하는 딕셔너리.

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:

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

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.

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

리스트 대신 제너레이터 함수를 사용하여 TarFile.extractall()로 tar 아카이브의 부분집합을 추출하는 방법:

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 모듈로 만들 수 있는 tar 형식은 세 가지입니다:

  • POSIX.1-1988 ustar 형식 (USTAR_FORMAT). 최대 256자 길이의 파일명과 최대 100자 링크 이름을 지원합니다. 최대 파일 크기는 8 GiB입니다. 이것은 오래되고 제한적이지만 널리 지원되는 형식입니다.

  • GNU tar 형식 (GNU_FORMAT). 긴 파일명과 링크 이름, 8GiB보다 큰 파일과 스파스(sparse) 파일을 지원합니다. 이것은 GNU/Linux 시스템에서 사실상 표준입니다. tarfile은 긴 이름에 대한 GNU tar 확장을 완전히 지원하며 스파스(sparse) 파일 지원은 읽기 전용입니다.

  • POSIX.1-2001 pax 형식 (PAX_FORMAT). 사실상 제한이 없는 가장 유연한 형식입니다. 긴 파일명과 링크 이름, 큰 파일을 지원하며 경로명을 이식성 있는 방식으로 저장합니다. GNU tar, bsdtar/libarchive 및 star를 포함한 최신 tar 구현은 확장된 pax 기능을 완벽하게 지원합니다; 일부 오래되었거나 유지 관리되지 않는 라이브러리는 그렇지 않을 수 있지만, pax 아카이브를 마치 범용적으로 지원되는 ustar 형식인 것처럼 취급해야 합니다. 새 아카이브의 현재 기본 형식입니다.

    다른 방법으로 저장할 수 없는 정보를 위해 추가 헤더를 사용하여 기존 ustar 형식을 확장합니다. pax 헤더에는 두 가지 종류가 있습니다: 확장(extended) 헤더는 후속 파일 헤더에만 영향을 미치며, 전역(global) 헤더는 전체 아카이브에 유효하며 뒤따르는 파일 모두에 영향을 미칩니다. pax 헤더의 모든 데이터는 이식성의 이유로 UTF-8로 인코딩됩니다.

읽을 수는 있지만 만들 수 없는 tar 형식의 변형이 더 있습니다:

  • 고대 V7 형식. 이것은 일반 파일과 디렉터리 만 저장하는 유닉스 7판(Unix Seventh Edition)에서 온 첫 번째 tar 형식입니다. 이름은 100자 이하여야 합니다. 사용자/그룹 이름 정보는 없습니다. ASCII가 아닌 문자가 있는 필드의 경우 일부 아카이브에서 헤더 체크섬이 잘못 계산되었습니다.

  • SunOS tar 확장 형식. 이 형식은 POSIX.1-2001 pax 형식의 변형이지만, 호환되지 않습니다.

유니코드 문제

tar 형식은 원래 파일 시스템 정보 보존에 중점을 두고 테이프 드라이브에서 백업하기 위해 고안되었습니다. 현재 tar 아카이브는 일반적으로 파일 배포와 네트워크를 통한 아카이브 교환에 사용됩니다. 원래 형식(다른 모든 형식의 기초)의 한 가지 문제점은 다른 문자 인코딩을 지원한다는 개념이 없다는 것입니다. 예를 들어, UTF-8 시스템에서 만들어진 일반 tar 아카이브는 ASCII가 아닌 문자가 포함되면 Latin-1 시스템에서 올바르게 읽을 수 없습니다. (파일명, 링크 이름, 사용자/그룹 이름과 같은) 텍스트 메타 데이터가 손상된 것으로 나타납니다. 불행히도, 아카이브의 인코딩을 자동 감지하는 방법은 없습니다. pax 형식은 이 문제를 해결하도록 설계되었습니다. 범용 문자 인코딩 UTF-8을 사용하여 ASCII가 아닌 메타 데이터를 저장합니다.

tarfile에서 문자 변환의 세부 사항은 TarFile 클래스의 encodingerrors 키워드 인자에 의해 제어됩니다.

encoding은 아카이브의 메타 데이터에 사용할 문자 인코딩을 정의합니다. 기본값은 sys.getfilesystemencoding() 이고, 또는 폴 백으로 'ascii'입니다. 아카이브를 읽거나 쓰는지에 따라, 메타 데이터를 디코딩하거나 인코딩해야 합니다. encoding이 올바르게 설정되지 않으면, 이 변환이 실패 할 수 있습니다.

errors 인자는 변환할 수 없는 문자를 처리하는 방법을 정의합니다. 가능한 값은 섹션 에러 처리기에 나열되어 있습니다. 기본 체계는 파이썬은 파일 시스템 호출에도 사용하는 'surrogateescape'입니다, 파일명, 명령 줄 인자 및 환경 변수를 참조하십시오.

PAX_FORMAT 아카이브(기본값)의 경우, 모든 메타 데이터가 UTF-8을 사용하여 저장기 때문에 encoding은 일반적으로 필요하지 않습니다. encoding은 바이너리 pax 헤더가 디코딩되거나 서로게이트 문자가 있는 문자열이 저장될 때와 같은 드문 경우에만 사용됩니다.