1. はじめに
Pythonでファイルやディレクトリのサイズを取得したいと思ったことはありませんか?
例えば、ログファイルのサイズを監視したり、バックアップ対象の容量を事前にチェックしたい場面など、ファイル・ディレクトリのサイズを取得する処理は実務でもよく登場します。
本記事では、Python初心者〜中級者向けに、os
やos.path
、pathlib
モジュールを活用して、ファイルやディレクトリのサイズを取得する方法を丁寧に解説します。具体的なコード例と実行結果を交えて、すぐに実務や学習に役立てられる内容となっています。
2. Pythonでファイルやディレクトリのサイズを取得する基本
2-1. ファイルサイズを取得する方法(os.path.getsize)
import os
file_path = "example.txt" # 任意のファイルパス
size = os.path.getsize(file_path) # ファイルサイズをバイト単位で取得
print(f"{file_path} のサイズは {size} バイトです")
実行結果:
example.txt のサイズは 1024 バイトです
2-2. ファイルサイズの単位を読みやすくする関数
def convert_size(size_bytes):
# サイズを読みやすい形式に変換
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.2f} PB"
print(convert_size(1048576)) # 1MBに相当
実行結果:
1.00 MB
2-3. pathlibを使ったファイルサイズの取得
from pathlib import Path
file = Path("example.txt")
print(f"{file.name} のサイズは {file.stat().st_size} バイトです")
実行結果:
example.txt のサイズは 1024 バイトです
3. よくある使い方・応用例
3-1. ディレクトリ全体のサイズを取得する
import os
def get_directory_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.isfile(fp):
total_size += os.path.getsize(fp)
return total_size
dir_path = "sample_dir"
size = get_directory_size(dir_path)
print(f"{dir_path} の合計サイズ: {convert_size(size)}")
実行結果:
sample_dir の合計サイズ: 12.48 MB
3-2. 特定の拡張子だけの合計サイズを取得
def get_size_by_extension(path, ext=".log"):
total_size = 0
for dirpath, _, filenames in os.walk(path):
for f in filenames:
if f.endswith(ext):
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
log_size = get_size_by_extension("logs", ".log")
print(f".logファイルの合計サイズ: {convert_size(log_size)}")
実行結果:
.logファイルの合計サイズ: 2.63 MB
4. 注意点・エラー対策
4-1. 存在しないファイル・ディレクトリを指定した場合
try:
size = os.path.getsize("not_exist.txt")
except FileNotFoundError:
print("指定したファイルが存在しません")
実行結果:
指定したファイルが存在しません
4-2. ディレクトリサイズ取得時のアクセス権限エラー
try:
size = get_directory_size("/root") # Linuxなどでアクセス権が必要な場合
except PermissionError:
print("ディレクトリへのアクセス権限がありません")
実行結果:
ディレクトリへのアクセス権限がありません
5. まとめ
本記事では、Pythonでファイルやディレクトリのサイズを取得する方法について解説しました。
os.path.getsize()
やpathlib
で簡単にファイルサイズを取得可能os.walk()
でディレクトリ全体のサイズを集計- 拡張子フィルタやバイト単位の変換関数でさらに実用的に
- エラー対策として
try-except
の活用が重要
この知識は、ログ管理やストレージ監視、バックアップ対象のチェックなど実務でも大いに役立ちます。Pythonを使って業務効率化を図りたい方には特におすすめの内容です。
Pythonでのファイル操作を習得すれば、他のタスク自動化にも応用できます。ぜひこの記事を参考に、自分のプロジェクトにも活かしてみてください。