管理を自動化するPython shutil ライブラリ
Python shutil ライブラリ完全ガイド
Python 標準ライブラリの shutil は、ファイルやディレクトリの操作を簡単に行うためのツールを提供します。本記事では、shutil の主要な機能とその活用方法について詳しく解説します。
1. shutil ライブラリの概要
shutilは、ファイルやディレクトリのコピー、移動、削除などの操作を簡単に行うための標準ライブラリです。- OS に依存せずに動作し、シンプルな API でファイル管理を実現できます。
- バックアップや一時ファイルの操作、自動化スクリプトに役立ちます。
インストール方法
shutil は Python の標準ライブラリなので、追加のインストールは不要です。
import shutil
import shutil
shutil.copy("source.txt", "destination.txt") # 内容のみコピー
shutil.copy2("source.txt", "destination2.txt") # メタデータもコピー
import shutil
shutil.copytree("source_dir", "destination_dir")
import shutil
shutil.move("old_name.txt", "new_name.txt")
shutil.move("file.txt", "backup_folder/")
import shutil
shutil.rmtree("folder_to_delete")
import shutil
usage = shutil.disk_usage("/")
print(f"合計: {usage.total} バイト")
print(f"使用済み: {usage.used} バイト")
print(f"空き容量: {usage.free} バイト")
import os
os.symlink("source.txt", "symlink.txt")
import tempfile
temp_dir = tempfile.mkdtemp()
print(f"作成された一時ディレクトリ: {temp_dir}")
import shutil
python_path = shutil.which("python")
print(f"Python の実行パス: {python_path}")
import os
os.mkdir("new_folder")
os.rmdir("new_folder")
import shutil
shutil.make_archive("backup", "zip", "source_dir")