MeWrite Docs

PermissionError: [Errno 13] Permission denied

Pythonでファイルやディレクトリへのアクセス権限がない場合に発生するエラー

概要

PermissionError は、ファイルやディレクトリに対する操作に必要な権限がない場合に発生するOSエラーです。

エラーメッセージ

PermissionError: [Errno 13] Permission denied: '/etc/passwd'
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\config'

原因

1. 読み取り権限がない

1
2
with open('/etc/shadow', 'r') as f:  # root権限が必要
    content = f.read()

2. 書き込み権限がない

1
2
with open('/usr/local/file.txt', 'w') as f:
    f.write('data')

3. ディレクトリへの書き込み

1
2
import os
os.mkdir('/root/new_dir')  # Permission denied

4. ファイルが使用中(Windows)

1
2
3
# 別のプロセスがファイルを開いている
with open('locked_file.txt', 'w') as f:
    f.write('data')  # PermissionError

解決策

1. 権限を確認

1
2
3
4
5
6
import os

path = '/path/to/file'
print(f"Readable: {os.access(path, os.R_OK)}")
print(f"Writable: {os.access(path, os.W_OK)}")
print(f"Executable: {os.access(path, os.X_OK)}")

2. 書き込み可能なディレクトリを使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import tempfile
import os

# 一時ディレクトリを使用
with tempfile.NamedTemporaryFile(delete=False) as f:
    f.write(b'data')
    print(f.name)

# ユーザーディレクトリを使用
home = os.path.expanduser('~')
file_path = os.path.join(home, 'myfile.txt')

3. 権限を変更(Linuxで自分のファイルの場合)

1
2
3
4
5
import os
import stat

# 書き込み権限を追加
os.chmod('myfile.txt', stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

4. 管理者権限で実行

1
2
3
4
# Linux/macOS
sudo python script.py

# Windows(管理者として実行)

5. try-exceptで処理

1
2
3
4
5
try:
    with open('/etc/shadow', 'r') as f:
        content = f.read()
except PermissionError:
    print("権限がありません。sudo で実行してください。")

6. Windowsでファイルロック対策

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import time

def write_with_retry(path, data, max_retries=5):
    for i in range(max_retries):
        try:
            with open(path, 'w') as f:
                f.write(data)
            return
        except PermissionError:
            if i < max_retries - 1:
                time.sleep(0.1)
            else:
                raise

関連エラー

関連エラー

Python の他のエラー

最終更新: 2025-12-17