MeWrite Docs

FileNotFoundError: No such file or directory

指定されたファイルが存在しない場合に発生するエラー

概要

FileNotFoundErrorは、存在しないファイルやディレクトリにアクセスしようとした場合に発生します。

エラーメッセージ

FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'

原因

  1. ファイルパスの間違い: タイプミスや相対パスの誤り
  2. 作業ディレクトリの違い: 実行場所が想定と異なる
  3. ファイルが存在しない: 削除されたか未作成

解決策

1. 絶対パスを使用

1
2
3
4
5
6
7
8
import os

# 相対パスではなく絶対パスを使用
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, 'data.txt')

with open(file_path, 'r') as f:
    content = f.read()

2. pathlibを使用

1
2
3
4
5
6
7
8
from pathlib import Path

file_path = Path(__file__).parent / 'data.txt'

if file_path.exists():
    content = file_path.read_text()
else:
    print(f"File not found: {file_path}")

3. 存在確認してから処理

1
2
3
4
5
6
7
8
9
import os

if os.path.exists('data.txt'):
    with open('data.txt', 'r') as f:
        content = f.read()
else:
    # ファイルを作成または別の処理
    with open('data.txt', 'w') as f:
        f.write('')

4. try-exceptでハンドリング

1
2
3
4
5
6
try:
    with open('data.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("ファイルが見つかりません")
    content = None

Python の他のエラー

最終更新: 2025-12-09