shutil --- 高水準のファイル操作

ソースコード: Lib/shutil.py


shutil モジュールはファイルやファイルの集まりに対する高水準の操作方法を多数提供します。特にファイルのコピーや削除のための関数が用意されています。個別のファイルに対する操作については、 os モジュールも参照してください。

警告

高水準のファイルコピー関数 (shutil.copy(), shutil.copy2()) でも、ファイルのメタデータの全てをコピーすることはできません。

POSIXプラットフォームでは、これはACLやファイルのオーナー、グループが失われることを意味しています。 Mac OSでは、リソースフォーク(resource fork)やその他のメタデータが利用されません。これは、リソースが失われ、ファイルタイプや生成者コード(creator code)が正しくなくなることを意味しています。 Windowsでは、ファイルオーナー、ACL、代替データストリームがコピーされません。

ディレクトリとファイルの操作

shutil.copyfileobj(fsrc, fdst[, length])

Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.

shutil.copyfile(src, dst, *, follow_symlinks=True)

Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible. src and dst are path-like objects or path names given as strings.

dst は完全な対象ファイル名でなければなりません。対象としてディレクトリ名を指定したい場合は copy() を参照してください。 srcdst が同じファイルだった場合、 SameFileError を送出します。

dst は書き込み可能でなければなりません。そうでない場合、 OSError 例外を送出します。 dst がすでに存在する場合、そのファイルは置き換えられます。キャラクタデバイスやブロックデバイスなどの特殊なファイルとパイプをこの関数でコピーすることはできません。

follow_symlinks が偽で src がシンボリックリンクの場合、 src のリンク先をコピーする代わりに新しいシンボリックリンクを作成します。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copyfile を送出します。

バージョン 3.3 で変更: 以前は OSError の代わりに IOError が送出されていました。 follow_symlinks 引数が追加されました。 dst を返すようになりました。

バージョン 3.4 で変更: Error の代わりに SameFileError を送出します。後者は前者のサブクラスなのでこの変更は後方互換です。

バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 プラットフォーム依存の効率的なコピー操作 を参照してください。

exception shutil.SameFileError

copyfile() のコピー元と先が同じファイルの場合送出されます。

バージョン 3.4 で追加.

shutil.copymode(src, dst, *, follow_symlinks=True)

Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings. If follow_symlinks is false, and both src and dst are symbolic links, copymode() will attempt to modify the mode of dst itself (rather than the file it points to). This functionality is not available on every platform; please see copystat() for more information. If copymode() cannot modify symbolic links on the local platform, and it is asked to do so, it will do nothing and return.

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copymode を送出します。

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

shutil.copystat(src, dst, *, follow_symlinks=True)

Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux, copystat() also copies the "extended attributes" where possible. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings.

follow_symlinks が偽の場合、 srcdst の両方がシンボリックリンクであれば、 copystat() はリンク先ではなくてシンボリックリンク自体を操作します。 src からシンボリックリンクの情報を読み込み、 dst のシンボリックリンクにその情報を書き込みます。

注釈

すべてのプラットフォームでシンボリックリンクの検査と変更ができるわけではありません。 Python はその機能が利用かどうかを調べる方法を用意しています。

  • os.chmod in os.supports_follow_symlinksTrue の場合 copystat() はシンボリックリンクのパーミッションを変更できます。

  • os.utime in os.supports_follow_symlinksTrue の場合 copystat() はシンボリックリンクの最終アクセス時間と最終変更時間を変更できます。

  • os.chflags in os.supports_follow_symlinksTrue の場合 copystat() はシンボリックリンクのフラグを変更できます。 (os.chflags がないプラットフォームもあります。)

機能の幾つか、もしくは全てが利用できないプラットフォームでシンボリックリンクを変更しようとした場合、 copystat() は可能な限り全てをコピーします。copystat() が失敗を返すことはありません。

より詳しい情報は os.supports_follow_symlinks を参照して下さい。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copystat を送出します。

バージョン 3.3 で変更: follow_symlinks 引数と Linux の拡張属性がサポートされました。

shutil.copy(src, dst, *, follow_symlinks=True)

ファイル src をファイルまたはディレクトリ dst にコピーします。 srcdst は両方共 term:path-like object または文字列でなければなりません。 dst がディレクトリを指定している場合、ファイルは dst の中に、 src のベースファイル名を使ってコピーされます。dst が既に存在するファイルを指定している場合、それは置き換えられます。新しく作成したファイルのパスを返します。

follow_symlinks が偽で、 src がシンボリックリンクの場合、 dst はシンボリックリンクとして作成されます。 follow_symlinks が真で src がシンボリックリンクの場合、 dst には src のリンク先のファイルがコピーされます。

copy() はファイルのデータとパーミッションをコピーします。 (os.chmod() を参照) その他の、ファイルの作成時間や変更時間などのメタデータはコピーしません。 コピー元のファイルのメタデータを保存したい場合は、 copy2() を利用してください。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copyfile を送出します。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copymode を送出します。

バージョン 3.3 で変更: follow_symlinks 引数が追加されました。新しく作成されたファイルのパスを返すようになりました。

バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 プラットフォーム依存の効率的なコピー操作 を参照してください。

shutil.copy2(src, dst, *, follow_symlinks=True)

copy2() はファイルのメタデータを保持しようとすることを除けば copy() と等価です。

When follow_symlinks is false, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly created dst symbolic link. However, this functionality is not available on all platforms. On platforms where some or all of this functionality is unavailable, copy2() will preserve all the metadata it can; copy2() never raises an exception because it cannot preserve file metadata.

copy2() はファイルのメタデータをコピーするために copystat() を利用します。シンボリックリンクのメタデータを変更するためのプラットフォームサポートについては copystat() を参照して下さい。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copyfile を送出します。

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copystat を送出します。

バージョン 3.3 で変更: follow_symlinks 引数が追加されました。 拡張ファイルシステム属性もコピーしようと試みます (現在は Linux のみ)。新しく作成されたファイルへのパスを返すようになりました。

バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 プラットフォーム依存の効率的なコピー操作 を参照してください。

shutil.ignore_patterns(*patterns)

このファクトリ関数は、 copytree() 関数の ignore 引数に渡すための呼び出し可能オブジェクトを作成します。 glob形式の patterns にマッチするファイルやディレクトリが無視されます。下の例を参照してください。

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)

Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. All intermediate directories needed to contain dst will also be created by default.

各ディレクトリのパーミッション、最終アクセス時間、最終変更時間は copystat() でコピーされます。それぞれのファイルは copy2() でコピーされます。

symlinks が真の場合、ソースツリー内のシンボリックリンクは新しいツリーでもシンボリックになり、元のシンボリックリンクのメタデータはプラットフォームが許す限りコピーされます。偽の場合や省略された場合、リンク先のファイルの内容とメタデータが新しいツリーにコピーされます。

symlinks が偽の場合、リンク先のファイルが存在しなければ、コピー処理終了時に送出される Error 例外のエラーリストに例外が追加されます。オプションの ignore_dangling_symlinks フラグを真に設定してこのエラーを送出させないこともできます。このオプションは os.symlink() をサポートしていないプラットフォーム上では効果がないことに注意してください。

ignorecopytree() が走査しているディレクトリと os.listdir() が返すその内容のリストを引数として受け取ることのできる呼び出し可能オブジェクトでなければなりません。 copytree() は再帰的に呼び出されるので、 ignore はコピーされる各ディレクトリ毎に呼び出されます。 ignore の戻り値はカレントディレクトリに相対的なディレクトリ名およびファイル名のシーケンス(すなわち第二引数の項目のサブセット)でなければなりません。それらの名前はコピー中に無視されます。 ignore_patterns() を用いて glob 形式のパターンによって無視する呼び出し可能オブジェクトを作成することが出来ます。

例外が発生した場合、理由のリストとともに Error を送出します。

copy_function は各ファイルをコピーするために利用される呼び出し可能オブジェクトでなければなりません。copy_function はコピー元のパスとコピー先のパスを引数に呼び出されます。デフォルトでは copy2() が利用されますが、同じ特徴を持つ関数 (shutil.copy() など) ならどれでも利用可能です。

If dirs_exist_ok is false (the default) and dst already exists, a FileExistsError is raised. If dirs_exist_ok is true, the copying operation will continue if it encounters existing directories, and files within the dst tree will be overwritten by corresponding files from the src tree.

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.copytree を送出します。

バージョン 3.2 で変更: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silence dangling symlinks errors when symlinks is false.

バージョン 3.3 で変更: symlinks が偽の場合メタデータをコピーします。 dst を返すようになりました。

バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 プラットフォーム依存の効率的なコピー操作 を参照してください。

バージョン 3.8 で変更: Added the dirs_exist_ok parameter.

shutil.rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onexc or onerror or, if both are omitted, exceptions are propagated to the caller.

この関数は ディレクトリ記述子への相対パス をサポートしています。

注釈

必要な fd ベースの関数をサポートしているプラットフォームでは、 シンボリックリンク攻撃に耐性のあるバージョンの rmtree() がデフォルトで利用されます。それ以外のプラットフォームでは、 rmtree() の実装はシンボリックリンク攻撃の影響を受けます。適当なタイミングと環境で攻撃者はファイルシステム上のシンボリックリンクを操作して、それ以外の方法ではアクセス不可能なファイルを削除することが出来ます。アプリケーションは、どちらのバージョンの rmtree() が利用されているかを知るために関数のデータ属性 rmtree.avoids_symlink_attacks を利用することができます。

If onexc is provided, it must be a callable that accepts three parameters: function, path, and excinfo.

The first parameter, function, is the function which raised the exception; it depends on the platform and implementation. The second parameter, path, will be the path name passed to function. The third parameter, excinfo, is the exception that was raised. Exceptions raised by onexc will not be caught.

The deprecated onerror is similar to onexc, except that the third parameter it receives is the tuple returned from sys.exc_info().

引数 path, dir_fd を指定して 監査イベント shutil.rmtree を送出します。

バージョン 3.3 で変更: プラットフォームが fd ベースの関数をサポートする場合に自動的に使用されるシンボリックリンク攻撃に耐性のあるバージョンが追加されました。

バージョン 3.8 で変更: Windows では、ディレクトリへのジャンクションを削除する際にリンク先ディレクトリにあるファイルを削除しなくなりました。

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

バージョン 3.12 で変更: Added the onexc parameter, deprecated onerror.

プラットフォームと実装がシンボリックリンク攻撃に耐性のあるバージョンの rmtree() を提供しているかどうかを示します。現在のところ、この属性は fd ベースのディレクトリアクセス関数をサポートしているプラットフォームでのみ真になります。

バージョン 3.3 で追加.

shutil.move(src, dst, copy_function=copy2)

Recursively move a file or directory (src) to another location and return the destination.

If dst is an existing directory or a symlink to a directory, then src is moved inside that directory. The destination path in that directory must not already exist.

If dst already exists but is not a directory, it may be overwritten depending on os.rename() semantics.

If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to the destination using copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created as the destination and src will be removed.

If copy_function is given, it must be a callable that takes two arguments, src and the destination, and will be used to copy src to the destination if os.rename() cannot be used. If the source is a directory, copytree() is called, passing it the copy_function. The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.

引数 src, dst` を指定して :ref:`監査イベント <auditing>` ``shutil.move を送出します。

バージョン 3.3 で変更: 異なるファイルシステムに対する明示的なシンボリックリンク処理が追加されました。これにより GNU mv の振る舞いに適応するようになります。 dst を返すようになりました。

バージョン 3.5 で変更: キーワード引数 copy_function が追加されました。

バージョン 3.8 で変更: ファイルのコピーをより効率的に行うため、プラットフォーム特有の高速なコピーを行うシステムコールが利用されることがあります。 プラットフォーム依存の効率的なコピー操作 を参照してください。

バージョン 3.9 で変更: srcdst が両方とも path-like object を受け付けるようになりました。

shutil.disk_usage(path)

指定されたパスについて、ディスクの利用状況を、名前付きタプル (named tuple) で返します。このタプルには total, used, free という属性があり、それぞれトータル、使用中、空きの容量をバイト単位で示します。 path はファイルまたはディレクトリです。

注釈

On Unix filesystems, path must point to a path within a mounted filesystem partition. On those platforms, CPython doesn't attempt to retrieve disk usage information from non-mounted filesystems.

バージョン 3.3 で追加.

バージョン 3.8 で変更: Windowsにおいても path にディレクトリだけでなくファイルを指定できるようになりました。

Availability: Unix, Windows。

shutil.chown(path, user=None, group=None)

指定された path のオーナー user と/または group を変更します。

user はシステムのユーザー名か uid です。 group も同じです。少なくともどちらかの引数を指定する必要があります。

内部で利用している os.chown() も参照してください。

引数 path, user, group を指定して 監査イベント shutil.chown を送出します。

バージョン 3.3 で追加.

shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)

cmd を実行しようとした時に実行される実行ファイルのパスを返します。 cmd を呼び出せない場合は None を返します。

modeos.access() に渡すパーミッションマスクで、デフォルトではファイルが存在して実行可能であることを確認します。

When no path is specified, the results of os.environ() are used, returning either the "PATH" value or a fallback of os.defpath.

On Windows, the current directory is prepended to the path if mode does not include os.X_OK. When the mode does include os.X_OK, the Windows API NeedCurrentDirectoryForExePathW will be consulted to determine if the current directory should be prepended to path. To avoid consulting the current working directory for executables: set the environment variable NoDefaultCurrentDirectoryInExePath.

Also on Windows, the PATHEXT variable is used to resolve commands that may not already include an extension. For example, if you call shutil.which("python"), which() will search PATHEXT to know that it should look for python.exe within the path directories. For example, on Windows:

>>> shutil.which("python")
'C:\\Python33\\python.EXE'

This is also applied when cmd is a path that contains a directory component:

>> shutil.which("C:\\Python33\\python")
'C:\\Python33\\python.EXE'

バージョン 3.3 で追加.

バージョン 3.8 で変更: bytes 型も使用できるようになりました。 cmdbytes 型の場合、戻り値も bytes 型です。

バージョン 3.12 で変更: On Windows, the current directory is no longer prepended to the search path if mode includes os.X_OK and WinAPI NeedCurrentDirectoryForExePathW(cmd) is false, else the current directory is prepended even if it is already in the search path; PATHEXT is used now even when cmd includes a directory component or ends with an extension that is in PATHEXT; and filenames that have no extension can now be found.

バージョン 3.12.1 で変更: On Windows, if mode includes os.X_OK, executables with an extension in PATHEXT will be preferred over executables without a matching extension. This brings behavior closer to that of Python 3.11.

exception shutil.Error

この例外は複数ファイルの操作を行っているときに生じる例外をまとめたものです。 copytree() に対しては例外の引数は3つのタプル(srcname, dstname, exception)からなるリストです。

プラットフォーム依存の効率的なコピー操作

Python 3.8 から、ファイルのコピーを伴う全ての関数 (copyfile(), copy(), copy2(), copytree(), および move()) はより効率的なファイルのコピーのためにプラットフォーム特有の "高速なコピー" を行うことがあります (bpo-33671 を参照してください). ここで "高速なコピー" とは、 "outfd.write(infd.read())" のようにPython が管理するユーザー空間のバッファを利用することを避け、コピー操作がカーネル空間内で行われることを意味します。

macOS では fcopyfile がファイルの内容(メタデータを除く)をコピーするために利用されます。

Linux では os.sendfile() が利用されます。

Windows では shutil.copyfile() はより大きなバッファサイズをデフォルトとして使います (6 KiB の代わりに 1 MiB が使われます)。また、 memoryview() ベースの変形である shutil.copyfileobj() が使われます。

高速なコピー操作が失敗して出力ファイルにデータが書き込まれなかった場合、shutil はユーザーへの通知なしでより効率の低い copyfileobj() 関数にフォールバックします。

バージョン 3.8 で変更.

copytree の例

ignore_patterns() ヘルパ関数を利用する例です:

from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

この例では、 .pyc ファイルと、 tmp で始まる全てのファイルやディレクトリを除いて、全てをコピーします。

ignore 引数にロギングさせる別の例です。

from shutil import copytree
import logging

def _logpath(path, names):
    logging.info('Working in %s', path)
    return []   # nothing will be ignored

copytree(source, destination, ignore=_logpath)

rmtree の例

This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onexc callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onexc=remove_readonly)

アーカイブ化操作

バージョン 3.2 で追加.

バージョン 3.5 で変更: xztar 形式のサポートが追加されました。

圧縮とアーカイブ化されているファイルの読み書きの高水準なユーティリティも提供されています。これらは zipfiletarfile モジュールに依拠しています。

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

アーカイブファイル (zip や tar) を作成してその名前を返します。

base_name is the name of the file to create, including the path, minus any format-specific extension.

format is the archive format: one of "zip" (if the zlib module is available), "tar", "gztar" (if the zlib module is available), "bztar" (if the bz2 module is available), or "xztar" (if the lzma module is available).

root_dir はアーカイブファイルのルートとなるディレクトリです。アーカイブに含まれる全てのパスは root_dir からの相対パスになります。これは、アーカイブファイルを生成する前に root_dir へ移動することに相当します。

base_dir はアーカイブを開始するディレクトリです。すなわち、 base_dir アーカイブに含まれるファイルとディレクトリに対する共通のプレフィックスになります。 base_dirroot_dir からの相対パスでなければなりません。 base_dirroot_dir を組み合わせて使う方法については base_dir を使ったアーカイブ化の例 を参照してください。

root_dirbase_dir のどちらも、デフォルトはカレントディレクトリです。

dry_run が真の場合、アーカイブは作成されませんが実行される操作は logger に記録されます。

ownergroup は、tar アーカイブを作成するときに使われます。デフォルトでは、カレントのオーナーとグループを使います。

loggerPEP 282 に互換なオブジェクトでなければなりません。これは普通は logging.Logger のインスタンスです。

verbose 引数は使用されず、非推奨です。

引数 base_name`, format, root_dir, base_dir``を指定して :ref:`監査イベント <auditing>` ``shutil.make_archive を送出します。

注釈

This function is not thread-safe when custom archivers registered with register_archive_format() do not support the root_dir argument. In this case it temporarily changes the current working directory of the process to root_dir to perform archiving.

バージョン 3.8 で変更: format="tar" で作成されたアーカイブでは、レガシーなGNU形式に代わってモダンな pax (POSIX.1-2001) 形式が使われます。

バージョン 3.10.6 で変更: This function is now made thread-safe during creation of standard .zip and tar archives.

shutil.get_archive_formats()

アーカイブ化をサポートしているフォーマットのリストを返します。返されるシーケンスのそれぞれの要素は、タプル (name, description) です。

デフォルトでは、 shutil は次のフォーマットを提供しています。

  • zip: ZIP ファイル (zlib モジュールが利用可能な場合)。

  • tar: 非圧縮の tar ファイル。 POSIX.1-2001 pax 形式が使われます。

  • gztar: gzip で圧縮された tar ファイル (zlib モジュールが利用可能な場合)。

  • bztar: bzip2 で圧縮された tar ファイル (bz2 モジュールが利用可能な場合)。

  • xztar: xz で圧縮された tar ファイル (lzma モジュールが利用可能な場合)。

register_archive_format() を使って、新しいフォーマットを登録したり、既存のフォーマットに独自のアーカイバを提供したりできます。

shutil.register_archive_format(name, function[, extra_args[, description]])

アーカイバをフォーマット name に登録します。

function はアーカイブのアンパックに使用される呼び出し可能オブジェクトです。funciton は作成するファイルの base_name、続いてアーカイブを開始する元の base_dir (デフォルトは os.curdir) を受け取ります。さらなる引数は、次のキーワード引数として渡されます: owner, group, dry_run ならびに logger (make_archive() に渡されます)。

If function has the custom attribute function.supports_root_dir set to True, the root_dir argument is passed as a keyword argument. Otherwise the current working directory of the process is temporarily changed to root_dir before calling function. In this case make_archive() is not thread-safe.

extra_args は、与えられた場合、 (name, value) の対のシーケンスで、アーカイバ呼び出し可能オブジェクトが使われるときに追加のキーワード引数として使われます。

description は、アーカイバのリストを返す get_archive_formats() で使われます。デフォルトでは空の文字列です。

バージョン 3.12 で変更: Added support for functions supporting the root_dir argument.

shutil.unregister_archive_format(name)

アーカイブフォーマット name を、サポートされているフォーマットのリストから取り除きます。

shutil.unpack_archive(filename[, extract_dir[, format[, filter]]])

アーカイブをアンパックします。 filename はアーカイブのフルパスです。

extract_dir はアーカイブをアンパックする先のディレクトリ名です。指定されなかった場合は現在の作業ディレクトリを利用します。

format はアーカイブフォーマットで、 "zip", "tar", "gztar", "bztar", "xztar" あるいは register_unpack_format() で登録したその他のフォーマットのどれかです。 指定されなかった場合、 unpack_archive() はアーカイブファイル名の拡張子に対して登録されたアンパッカーを利用します。 アンパッカーが見つからなかった場合、 ValueError を発生させます。

The keyword-only filter argument is passed to the underlying unpacking function. For zip files, filter is not accepted. For tar files, it is recommended to set it to 'data', unless using features specific to tar and UNIX-like filesystems. (See Extraction filters for details.) The 'data' filter will become the default for tar files in Python 3.14.

引数 filename, extract_dir, format を指定して 監査イベント shutil.unpack_archive を送出します。

警告

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of the path specified in the extract_dir argument, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".

バージョン 3.7 で変更: filenameextract_dirpath-like object を受け付けるようになりました。

バージョン 3.12 で変更: Added the filter argument.

shutil.register_unpack_format(name, extensions, function[, extra_args[, description]])

アンパック用のフォーマットを登録します。 name はフォーマット名で、 extensions はそのフォーマットに対応する拡張子 (例えば Zip ファイルに対して .zip) のリストです。

function is the callable that will be used to unpack archives. The callable will receive:

  • the path of the archive, as a positional argument;

  • the directory the archive must be extracted to, as a positional argument;

  • possibly a filter keyword argument, if it was given to unpack_archive();

  • additional keyword arguments, specified by extra_args as a sequence of (name, value) tuples.

フォーマットの説明として description を指定することができます。これは get_unpack_formats() 関数によって返されます。

shutil.unregister_unpack_format(name)

アンパックフォーマットを登録解除します。 name はフォーマットの名前です。

shutil.get_unpack_formats()

登録されているすべてのアンパックフォーマットをリストで返します。戻り値のリストの各要素は (name, extensions, description) の形のタプルです。

デフォルトでは、 shutil は次のフォーマットを提供しています。

  • zip: ZIP ファイル (対応するモジュールが利用可能な場合にのみ圧縮ファイルはアンパックされます)。

  • tar: 圧縮されていない tar ファイル。

  • gztar: gzip で圧縮された tar ファイル (zlib モジュールが利用可能な場合)。

  • bztar: bzip2 で圧縮された tar ファイル (bz2 モジュールが利用可能な場合)。

  • xztar: xz で圧縮された tar ファイル (lzma モジュールが利用可能な場合)。

register_unpack_format() を使って新しいフォーマットや既存のフォーマットに対する別のアンパッカーを登録することができます。

アーカイブ化の例

この例では、ユーザの .ssh ディレクトリにあるすべてのファイルを含む、 gzip された tar ファイルアーカイブを作成します:

>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'

結果のアーカイブは、以下のものを含みます:

$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
-rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
-rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
-rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
-rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
-rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
-rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
-rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts

base_dir を使ったアーカイブ化の例

この例では、 上記の例 と同じく make_archive() の使い方を示しますが、ここでは特に base_dir の使い方を説明します。以下のようなディレクトリ構造があるとします。

$ tree tmp
tmp
└── root
    └── structure
        ├── content
            └── please_add.txt
        └── do_not_add.txt

作成するアーカイブには please_add.txt が含まれますが、いっぽう do_not_add.txt は含まないようにします。この場合以下のようにします。

>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> make_archive(
...     archive_name,
...     'tar',
...     root_dir='tmp/root',
...     base_dir='structure/content',
... )
'/Users/tarek/my_archive.tar'

アーカイブに含まれるファイルをリストすると、以下のようになります。

$ python -m tarfile -l /Users/tarek/myarchive.tar
structure/content/
structure/content/please_add.txt

出力ターミナルのサイズの取得

shutil.get_terminal_size(fallback=(columns, lines))

ターミナルウィンドウのサイズを取得します。

幅と高さについて、それぞれ COLUMNSLINES という環境変数をチェックします。その変数が定義されていて値が正の整数であればそれを利用します。

典型的な COLUMNSLINES が定義されていない場合には、 sys.__stdout__ に接続されているターミナルに os.get_terminal_size() を呼び出して問い合わせます。

システムが対応していない場合やターミナルに接続していないなどの理由でターミナルサイズの問い合わせに失敗した場合、 fallback 引数に与えられた値を利用します。 fallback のデフォルト値は (80, 24) で、これは多くのターミナルエミュレーターが利用しているデフォルトサイズです。

戻り値は os.terminal_size 型の名前付きタプルです。

参考: The Single UNIX Specification, Version 2, Other Environment Variables.

バージョン 3.3 で追加.

バージョン 3.11 で変更: The fallback values are also used if os.get_terminal_size() returns zeroes.