Geminiを使います。
Gemini API
Google Accountは持っているとします。
API Key
***************************************
visual studio code / 設定
Cline
Use your own API key
[API Provider]
Google Gemini
[Gemini API Key]
***************************************
[Model]
gemini-2.5-pro-exp-03-25
[Done] (上に戻ります)
Auto-approve: None
ときどき欲しくなる機能を作ってもらう
前の記事と同じです。
create a python script that outputs a list of files and their sizes under a specified folder.
the folder is specified as an argument at run time.
please output file sizes in descending order in human-friendly units.
for directory, recursively get the total file size under the directory.
for directory, output a list of directories. for each directory, output the total file size under that directory.
費用
無料。
output
file nameは変えてます。
file_sizes_gemini.py
import os
import argparse
from pathlib import Path
def get_human_readable_size(size_bytes):
"""Converts a size in bytes to a human-readable string."""
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = 0
while size_bytes >= 1024 and i < len(size_name) - 1:
size_bytes /= 1024.0
i += 1
s = f"{size_bytes:.2f}"
# Remove trailing .00
if s.endswith(".00"):
s = s[:-3]
return f"{s}{size_name[i]}"
def get_dir_size(start_path='.'):
"""Recursively calculates the total size of files in a directory."""
total_size = 0
try:
# Use scandir for potentially better performance
for entry in os.scandir(start_path):
try:
if entry.is_file(follow_symlinks=False):
total_size += entry.stat().st_size
elif entry.is_dir(follow_symlinks=False):
total_size += get_dir_size(entry.path)
except OSError:
# Ignore files/dirs we can't access or broken symlinks
pass
except OSError:
# Ignore directories we can't access at the top level
pass
return total_size
def list_files_and_sizes(folder_path):
"""Lists files and directories with their sizes in a given folder."""
files_info = []
dirs_info = []
target_path = Path(folder_path)
if not target_path.is_dir():
print(f"Error: '{folder_path}' is not a valid directory.")
return
try:
# Use scandir for potentially better performance and type checking
for entry in os.scandir(target_path):
try:
if entry.is_file(follow_symlinks=False):
size = entry.stat().st_size
files_info.append((entry.name, size))
elif entry.is_dir(follow_symlinks=False):
# Get size only once
dir_size = get_dir_size(entry.path)
dirs_info.append((entry.name, dir_size))
# Silently ignore other types like symlinks at the top level
except OSError as e:
print(f"Could not access {entry.name}: {e}")
except OSError as e:
print(f"Could not read directory {folder_path}: {e}")
return
# Sort by size descending
files_info.sort(key=lambda x: x[1], reverse=True)
dirs_info.sort(key=lambda x: x[1], reverse=True)
print(f"\n--- Files in {folder_path} ---")
if files_info:
max_name_len = max(len(name) for name, size in files_info) if files_info else 0
for name, size in files_info:
print(f"{name:<{max_name_len}} : {get_human_readable_size(size)}")
else:
print("No files found.")
print(f"\n--- Directories in {folder_path} (Total Size) ---")
if dirs_info:
max_name_len = max(len(name) for name, size in dirs_info) if dirs_info else 0
for name, size in dirs_info:
print(f"{name + '/':<{max_name_len+1}} : {get_human_readable_size(size)}")
else:
print("No directories found.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="List files and directories with their sizes (descending order) in a specified folder.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter # Show default values in help
)
parser.add_argument("folder", help="The path to the folder to analyze.")
args = parser.parse_args()
list_files_and_sizes(args.folder)
まとめ
file sizeもdirectoryも降順です。そして、見やすく出力してくれている。
PerplexityにはPerplexityが得意することを任せることにしましょう。
肩が凝るとかでなく、頭が疲れるけど疲れる価値はあると思います。
他にも色々と作ってもらっていたら2日で無料で使える上限に達してしまいました。
広告
IT開発関連書とビジネス書が豊富な翔泳社の通販『SEshop』
さくらのレンタルサーバ

ムームードメイン

Oisix(おいしっくす)

らでぃっしゅぼーや

珈琲きゃろっと

エプソムソルト
