I/O operation not supported
Production Risk
Programming error; always open files in the correct mode.
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.
- 1Writing to a file opened in read-only mode ('r')
- 2Calling seek() on sys.stdin or a network socket (non-seekable)
- 3Reading from a file opened with 'w'
Writing to a file opened in 'r' mode.
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
# 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
import sys
if sys.stdin.seekable():
sys.stdin.seek(0)
else:
# stdin from pipe — not seekable
passWhy this works
stream.seekable(), readable(), and writable() return booleans indicating supported operations.
with open('/etc/hostname', 'r') as f:
f.write('newname') # io.UnsupportedOperation: not writabletry:
f.write(data)
except io.UnsupportedOperation as e:
print(f'Operation not supported: {e}')# 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() # worksPython Docs — io module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev