Pythonでディレクトリの総サイズを計算する方法
Pythonでディレクトリの総サイズを計算する方法
Pythonでディレクトリの総サイズを計算するための手順を説明します。
- 必要なモジュールをインポートします:
import os
- ファイルまたはディレクトリのサイズを計算するための関数を定義します:
def get_size(path):
total_size = 0
# パスがファイルであれば、そのサイズを返します
if os.path.isfile(path):
return os.path.getsize(path)
# パスがディレクトリであれば、その内容を繰り返し処理します
for dirpath, dirnames, filenames in os.walk(path):
# ディレクトリ内のすべてのファイルの合計サイズを計算します
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
- ユーザーにディレクトリのパスを入力するように促します:
directory = input("ディレクトリのパスを入力してください: ")
get_size()関数をディレクトリのパスと共に呼び出し、結果を表示します:
size = get_size(directory)
print("総サイズ:", size, "バイト")
以上です!プログラムを実行すると、ディレクトリのパスの入力を求められます。パスを指定すると、ディレクトリの総サイズが計算され、バイト単位で表示されます。
以下に完全な例を示します:
import os
def get_size(path):
total_size = 0
if os.path.isfile(path):
return os.path.getsize(path)
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
directory = input("ディレクトリのパスを入力してください: ")
size = get_size(directory)
print("総サイズ:", size, "バイト")
特定のユースケースに合わせて必要に応じてコードを変更してください。