io.UnsupportedOperation
PythonERRORCommonOS ErrorHIGH confidence

I/O operation not supported

Production Risk

Programming error; always open files in the correct mode.

What this means

Raised when an I/O operation is called on a stream that does not support it — for example, writing to a read-only file, seeking on a non-seekable stream, or reading from a write-only file.

Why it happens
  1. 1Writing to a file opened in read-only mode ('r')
  2. 2Calling seek() on sys.stdin or a network socket (non-seekable)
  3. 3Reading from a file opened with 'w'
How to reproduce

Writing to a file opened in 'r' mode.

trigger — this will error
trigger — this will error
with open('/etc/hostname', 'r') as f:
    f.write('newname')

expected output

io.UnsupportedOperation: not writable

Fix 1

Open the file in the correct mode

WHEN When UnsupportedOperation is raised

Open the file in the correct mode
# Read mode  → 'r' (default)
# Write mode → 'w' (truncates) or 'a' (append)
# Read+write → 'r+' (must exist) or 'w+' (truncates)
with open('file.txt', 'w') as f:
    f.write('content')

Why this works

Python file modes map directly to POSIX open() flags; 'r' sets O_RDONLY, 'w' sets O_WRONLY|O_CREAT|O_TRUNC.

Fix 2

Check seekable() before seeking

WHEN Working with streams that may not support seek

Check seekable() before seeking
import sys

if sys.stdin.seekable():
    sys.stdin.seek(0)
else:
    # stdin from pipe — not seekable
    pass

Why this works

stream.seekable(), readable(), and writable() return booleans indicating supported operations.

Code examples
Triggerpython
with open('/etc/hostname', 'r') as f:
    f.write('newname')  # io.UnsupportedOperation: not writable
Handle with try/exceptpython
try:
    f.write(data)
except io.UnsupportedOperation as e:
    print(f'Operation not supported: {e}')
Avoid by opening in the correct modepython
# Open for writing explicitly
with open('file.txt', 'w') as f:
    f.write('data')  # works

# Open for reading
with open('file.txt', 'r') as f:
    content = f.read()  # works
Sources
Official documentation ↗

Python Docs — io module

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors