Python file.writable() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
file method

Definition

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)
CallWhat 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 ValueDescription
TrueWriting methods are allowed.
FalseWriting 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")

How It Works

  1. Class follows mode. Write modes give a BufferedWriter, read mode a BufferedReader, and "r+b" a BufferedRandom.
  2. Only "rb" is read-only. The three other modes report True.
  3. 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())

How It Works

  1. Writable handle. On the "w" file, save() passes along the count from write(): 12 characters.
  2. Read-only handle. On the "r" file the helper skips the write and returns 0, and the file still holds chapter one only.
  3. 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())

How It Works

  1. Default mode is "r". Writing raises io.UnsupportedOperation, and writable() confirms why.
  2. Read and write. "r+" keeps the existing content and allows both directions.
  3. Write after reading to the end. read() left the position at the end of the file, so the new line is added after the old one.

Frequently Asked Questions

False. Use "r+" to read and write an existing file, or "a" to add to the end.
"w", "a", "x", and any mode with "+", such as "r+", "w+", and "a+", plus their binary versions.
io.UnsupportedOperation with a message like "not writable". It is a subclass of OSError and ValueError.
No. Permissions are checked when open() runs, which raises PermissionError if writing is not allowed. writable() only reflects the mode.
"w" empties the file (or creates it) and starts at position 0. "r+" requires an existing file, keeps its content, and also allows reading.

Next: file.write()

Write a string (text mode) or bytes (binary mode) and return how many were written.

write() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful