AI Agents · レッスン

エージェントコンテキストでのファイルの読み書き

エージェントツールからopen()、pathlib.Pathを使い、CSV/JSON/TXTファイルを読み込みます。

レッスン 1/413 ステップ

「エージェントコンテキストでのファイルの読み書き」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

エージェントにとってファイルI/Oが重要な理由

エージェントは、設定の読み込み、中間結果の保存、出力レポートの書き込みを頻繁に行う必要があります。Pythonでファイルを扱う主な方法は、組み込みのopen()関数と、現代的なpathlibモジュールの2つです。どちらも必須の知識です。

すべてのファイル操作では、エラーが発生してもファイルが確実に閉じられるよう、コンテキストマネージャー(with文)を使用してください。

with open('config.txt', 'w', encoding='utf-8') as f:
    f.write('model=gpt-4o-mini\nmax_steps=20\n')

with open('config.txt', 'r', encoding='utf-8') as f:
    content = f.read()

from pathlib import Path
content = Path('config.txt').read_text(encoding='utf-8')

print(content)

open()でファイルを読み込む

open()関数には、ファイル名とモードを指定します。テキストを読み込む場合は、モード'r'を使用します。ファイル全体を一度に.read()で読み込むことも、.readline()で1行ずつ読み込むことも、.readlines()ですべての行をリストに読み込むこともできます。

プラットフォーム固有のエンコーディングによる予期しない問題を避けるため、必ずencoding='utf-8'を指定してください。

with open('report.txt', 'w', encoding='utf-8') as f:
    f.write('Quarterly agent report body text.')
with open('large_log.txt', 'w', encoding='utf-8') as f:
    f.write('INFO: started\nERROR: timeout\nINFO: done\n')
with open('tasks.txt', 'w', encoding='utf-8') as f:
    f.write('task one\ntask two\n')

with open('report.txt', 'r', encoding='utf-8') as f:
    full_text = f.read()
    print(f'Read {len(full_text)} characters')

with open('large_log.txt', 'r', encoding='utf-8') as f:
    for line in f:
        line = line.rstrip('\n')
        if 'ERROR' in line:
            print('Found error:', line)

with open('tasks.txt', 'r', encoding='utf-8') as f:
    tasks = f.readlines()
    tasks = [t.strip() for t in tasks]
print('Tasks:', tasks)

open()でファイルを書き込む

書き込み(新規作成または上書き)にはモード'w'、追記には'a'、排他的な新規作成には'x'を使用します。'x'はファイルが存在すると失敗します。モード'w'は最初にファイルを切り詰めるため、既存のデータを扱う際は注意してください。

# Write a new file (or overwrite)
results = ['Task 1 complete', 'Task 2 complete', 'Task 3 failed']

with open('results.txt', 'w', encoding='utf-8') as f:
    for result in results:
        f.write(result + '\n')

# Append to existing file (add without overwriting)
with open('agent_log.txt', 'a', encoding='utf-8') as f:
    f.write('2026-05-29 14:30: Agent completed batch\n')

# Create exclusively — error if file already exists
try:
    with open('unique_report.txt', 'x', encoding='utf-8') as f:
        f.write('This file is new')
except FileExistsError:
    print('File already exists, skipping')

# --- demo ---
print('results.txt contents:')
with open('results.txt', encoding='utf-8') as f:
    print(f.read())

# Try the exclusive create again now that the file exists
try:
    with open('unique_report.txt', 'x', encoding='utf-8') as f:
        f.write('This file is new')
except FileExistsError:
    print('File already exists, skipping')

pathlib.Path — 現代的なファイル操作

pathlib.Pathは、ファイルパスをオブジェクト指向で扱う方法を提供します。os.pathよりも読みやすく、プラットフォーム間で異なるパス区切り文字を自動的に処理します。単純な読み書き操作には、read_text()とwrite_text()を使うのが最もすっきりした方法です。

from pathlib import Path

base = Path('agent_workspace')
base.mkdir(exist_ok=True)
config_file = base / 'config.json'
config_file.write_text('{"model": "gpt-4o-mini"}', encoding='utf-8')

if config_file.exists():
    content = config_file.read_text(encoding='utf-8')
    print('Config:', content)

output = base / 'output' / 'report.txt'
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text('Agent report\nLine 2', encoding='utf-8')

Path('image.png').write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(100)))
binary_data = Path('image.png').read_bytes()
print(f'File size: {len(binary_data)} bytes')

JSONファイルの読み書き

エージェントは、構造化されたデータをJSONファイルとして頻繁にやり取りします。JSONファイルの解析にはjson.load()を、書き込みにはjson.dump()を使用します。人間が読みやすい出力にするため、常にindent=2を使用し、Unicode文字を保持するためにensure_ascii=Falseを指定してください。

import json
from pathlib import Path

config_path = Path('agent_config.json')
config_path.write_text(json.dumps({'max_retries': 5, 'model': 'gpt-4o-mini'}), encoding='utf-8')

with open(config_path, 'r', encoding='utf-8') as f:
    config = json.load(f)

print('Max retries:', config.get('max_retries', 3))
print('Model:', config.get('model', 'gpt-4o-mini'))

results = {
    'run_id': 'run-001',
    'status': 'completed',
    'items_processed': 142,
    'errors': []
}

with open('results.json', 'w', encoding='utf-8') as f:
    json.dump(results, f, indent=2, ensure_ascii=False)

print('Results written to results.json')

コンテキストマネージャー — 正しい使い方

with文(コンテキストマネージャー)を使うと、ブロックの終了時にファイルが確実に閉じられます。読み取りの途中で例外が発生した場合も同様です。with文を使わないと、ファイルが開いたままになってファイルディスクリプターが枯渇し、ファイルハンドル数に制限のあるシステムでクラッシュする可能性があります。

with open('data.txt', 'w', encoding='utf-8') as f:
    f.write('sample content')

f = open('data.txt', 'r')
try:
    content = f.read()
finally:
    f.close()

with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()

with open('input.txt', 'w', encoding='utf-8') as f:
    f.write('hello\nworld\n')

with open('input.txt', 'r') as infile, \
     open('output.txt', 'w') as outfile:
    for line in infile:
        processed = line.upper()
        outfile.write(processed)

print('Done:', content)

バイナリファイルの操作

バイナリファイル(画像、PDF、音声)の読み込みにはモード'rb'を、書き込みには'wb'を使用します。バイナリデータをテキストとしてデコードしようとしてはいけません。pathlibのread_bytes()/write_bytes()、またはopen()のバイナリモードを使用してください。

from pathlib import Path
import base64

image_path = Path('screenshot.png')
image_path.write_bytes(b'\x89PNG\r\n\x1a\n' + bytes(range(50)))

image_bytes = image_path.read_bytes()
print(f'Image size: {len(image_bytes)} bytes')

image_b64 = base64.b64encode(image_bytes).decode('utf-8')
print(f'Base64 length: {len(image_b64)}')

response_bytes = b'...binary content from API...'
output_path = Path('output') / 'generated_image.png'
output_path.parent.mkdir(exist_ok=True)
output_path.write_bytes(response_bytes)
print('Wrote', output_path)

エンコーディングと改行に関する問題への対処

システムによって使用する改行文字が異なります(Linux/macOSでは\n、Windowsでは\r\n)。常にencoding='utf-8'を指定し、newline=None(デフォルト)でPythonに改行処理を任せてください。BOM(バイトオーダーマーク)付きのファイルには、encoding='utf-8-sig'を使用します。

with open('data.txt', 'w', encoding='utf-8') as f:
    f.write('hello world')
with open('windows_export.csv', 'wb') as f:
    f.write('name,email\n'.encode('utf-8'))
with open('unknown_encoding.txt', 'wb') as f:
    f.write('cafe resume'.encode('latin-1'))

with open('data.txt', 'r', encoding='utf-8') as f:
    text = f.read()

with open('windows_export.csv', 'r', encoding='utf-8-sig') as f:
    content = f.read()

try:
    with open('unknown_encoding.txt', 'r', encoding='utf-8') as f:
        text = f.read()
except UnicodeDecodeError:
    with open('unknown_encoding.txt', 'r',
               encoding='utf-8', errors='replace') as f:
        text = f.read()
    print('Warning: file had encoding errors (replaced with ?)')

print('All reads completed. csv content:', repr(content))

効率的な1行ずつの処理

大きなファイル(ログファイルやデータセット)では、.read()ですべてをメモリに読み込むのは避けてください。ファイルオブジェクトを直接反復処理すると、Pythonが1行ずつ読み込むため、ファイルサイズに関係なくメモリ使用量を一定に保てます。

from pathlib import Path

def process_large_log(log_path):
    error_count = 0
    processed = 0

    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:  # reads one line at a time
            line = line.strip()
            if not line:
                continue

            processed += 1
            if '[ERROR]' in line:
                error_count += 1
                # Process error immediately without storing all lines
                handle_error(line)

    print(f'Processed {processed} lines, {error_count} errors')

def handle_error(line):
    print(f'Error found: {line[:80]}')

# --- demo ---
with open('demo_agent.log', 'w', encoding='utf-8') as f:
    f.write('[INFO] agent started\n')
    f.write('[ERROR] timeout calling tool search_web\n')
    f.write('[INFO] retrying\n')
    f.write('[ERROR] tool search_web failed again\n')

process_large_log('demo_agent.log')

ディレクトリの作成と管理

ファイルを書き込む前に、親ディレクトリが存在することを確認してください。Path.mkdir(parents=True, exist_ok=True)を使用すると、すでに存在する場合もエラーを発生させずに、入れ子になったディレクトリを作成できます。これは、出力ファイルを生成するエージェントの開始時によく行う初期設定です。

from pathlib import Path
import datetime

# Create output directory structure
today = datetime.date.today().isoformat()  # '2026-05-29'
output_dir = Path('agent_output') / today / 'reports'
output_dir.mkdir(parents=True, exist_ok=True)

print(f'Output directory: {output_dir}')

# Now write files safely
for i in range(3):
    report_path = output_dir / f'report_{i:02d}.json'
    report_path.write_text(
        '{"status": "ok"}',
        encoding='utf-8'
    )

# List all created files
for f in output_dir.iterdir():
    print(f'  {f.name}: {f.stat().st_size} bytes')

エージェントでのファイルパスに関するベストプラクティス

エージェントでは、絶対パス、または明確に定義した基準ディレクトリからの相対パスを使用してください。エージェントは異なる場所から起動されることが多いため、現在の作業ディレクトリ(./)に依存してはいけません。Path(__file__).parentを使用すると、スクリプトのディレクトリを基準として取得できます。

from pathlib import Path

# Get absolute path relative to THIS script's location
SCRIPT_DIR = Path(__file__).parent
DATA_DIR = SCRIPT_DIR / 'data'
OUTPUT_DIR = SCRIPT_DIR / 'output'

# Always resolve to absolute path before use
config = DATA_DIR / 'config.json'
print('Config path:', config.resolve())

# Check if file exists before reading
if config.exists():
    import json
    with open(config, 'r', encoding='utf-8') as f:
        settings = json.load(f)
else:
    print(f'Config not found at {config.resolve()}')
    settings = {}

# Safe output path
result_path = (OUTPUT_DIR / 'result.json').resolve()
print('Will write to:', result_path)

クイックチェック:コンテキストマネージャー

ファイルI/Oのベストプラクティスについての理解度を確認しましょう。

ファイルI/Oのまとめ

これで、エージェントのコードでファイルを操作するための確かな基礎が身につきました。

  • 読み込みにはopen('file', 'r', encoding='utf-8')、書き込みには'w'、追記には'a'を使用します
  • ファイルが確実に閉じられるよう、常にwith文を使用します
  • pathlib.Pathを使うと、read_text()/write_text()によって、すっきりしたクロスプラットフォーム対応のパス処理ができます
  • 構造化データにはjson.load(f) / json.dump(data, f, indent=2)を使用します
  • 大きなファイルでは、メモリ使用量を抑えるために1行ずつ処理します
  • 基準ディレクトリにはPath(__file__).parentを使用し、cwdには決して依存しません
無料で開始

AI チューターと学ぶ AI Agents — 無料

ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。

コース
60
レッスン
239

よくある質問

「エージェントコンテキストでのファイルの読み書き」レッスンは無料ですか?

はい。「エージェントコンテキストでのファイルの読み書き」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「エージェントコンテキストでのファイルの読み書き」で何を学びますか?

エージェントツールからopen()、pathlib.Pathを使い、CSV/JSON/TXTファイルを読み込みます。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「エージェントコンテキストでのファイルの読み書き」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. エージェントコンテキストでのファイルの読み書き
  2. ディレクトリトラバーサルとファイル探索
  3. ファイル形式の処理:CSV、JSON、TXT
  4. エラーハンドリングを伴う安全なファイル操作
← AI Agentsに戻る