writable() returns True when write(), writelines(), and truncate() are allowed on the stream, and False when they would raise.
For files it follows the mode: "w", "a", "x", and any mode with "+" are writable; plain "r" is not.
file.writable() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).
Syntax
Call it with no arguments on an open stream.
python
if f.writable():
f.write(text)
Call
What it does
open(path, "rb").writable()
False: read-only.
open(path, "ab").writable()
True: appends at the end.
open(path, "r+b").writable()
True: read and write.
"x" is writable too, but open() raises FileExistsError if the file already exists.
Method signatures
python
file.writable() # -> bool
# IOBase.writable() returns False unless a subclass overrides it
Parameters
writable() takes no parameters.
Return Value
Return Value
Description
True
Writing methods are allowed.
False
Writing would raise io.UnsupportedOperation.
Python Examples
Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.
Example 1 — Compare writable() Across Binary Modes
Open a cache file with four binary modes, then try exclusive creation on the existing file.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "cache.bin")
for mode in ("wb", "rb", "ab", "r+b"):
with open(path, mode) as f:
print(mode, type(f).__name__, f.writable())
try:
open(path, "xb")
except FileExistsError:
print("xb refuses to overwrite an existing file")
Output
wb BufferedWriter True
rb BufferedReader False
ab BufferedWriter True
r+b BufferedRandom True
xb refuses to overwrite an existing file
How It Works
Class follows mode. Write modes give a BufferedWriter, read mode a BufferedReader, and "r+b" a BufferedRandom.
Only "rb" is read-only. The three other modes report True.
Exclusive create."xb" would be writable, but open() raises FileExistsError because the cache already exists, so no file object is created.
Example 2 — Write Only When the Stream Allows It
A save() helper returns the number of characters written, or 0 for read-only streams.
python
import io
import os
import tempfile
def save(stream, text):
if not stream.writable():
return 0
return stream.write(text)
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "draft.txt")
with open(path, "w", encoding="utf-8") as f:
print(save(f, "chapter one\n"))
with open(path, encoding="utf-8") as f:
print(save(f, "chapter two\n"), f.read().strip())
memory = io.StringIO()
print(save(memory, "scratch"), memory.getvalue())
Output
12
0 chapter one
7 scratch
How It Works
Writable handle. On the "w" file, save() passes along the count from write(): 12 characters.
Read-only handle. On the "r" file the helper skips the write and returns 0, and the file still holds chapter one only.
In-memory works too.io.StringIO is writable, so the helper stores scratch and returns 7.
Example 3 — Reopen a Read-Only File as r+ to Update It
A visit counter file: writing fails in "r" mode, then succeeds after reopening with "r+".
python
import io
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "visits.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("visits=1\n")
with open(path, encoding="utf-8") as f:
try:
f.write("visits=2\n")
except io.UnsupportedOperation:
print("mode 'r' is read-only:", f.writable())
with open(path, "r+", encoding="utf-8") as f:
print("mode 'r+':", f.writable(), f.read().strip())
f.write("visits=2\n")
with open(path, encoding="utf-8") as f:
print(f.read().splitlines())