Python 3.3+Exceptionsexception
PermissionError
built-in exceptions
Raised on an attempt to perform an operation without the access rights the file or resource requires.
Syntax
raise PermissionError('нет доступа')
A subclass of OSError, raised by the operation itself (open, os.remove, a write) and never in advance — which makes an os.access pre-check both useless and racy; wrap the real call in try instead. On Windows it also shows up in surprising places: opening a directory with open(), or deleting or renaming a file that another program still holds open.
Examples
import os
import tempfile
from pathlib import Path
# Права — свойство ОС И пользователя. Под администратором (а в контейнере
# процесс часто идёт от root) запись разрешена даже в файл «только для чтения»,
# поэтому ожидания здесь помечены средозависимыми: карточка показывает ФОРМУ
# обработки, а не гарантированный исход. Прежний пример читал '/etc/shadow' —
# файла с таким именем нет ни на Windows, ни на macOS.
path = Path(tempfile.mkdtemp()) / 'readonly.txt'
path.write_text('данные', encoding='utf-8')
os.chmod(path, 0o444)
try:
with open(path, 'w', encoding='utf-8') as f:
f.write('перезапись')
print('запись разрешена — у процесса права администратора') # → ?
except PermissionError:
print('нет прав на запись') # → ?
See also
Open in the full glossarydocs.python.orgReport an inaccuracy