A text file in Python is built in layers: a TextIOWrapper on top of a binary buffer (BufferedReader, BufferedWriter, or BufferedRandom) on top of a raw FileIO. detach()unplugs the top layer and hands you the one below.
The layer you detached from becomes unusable: almost every operation on it raises ValueError. The returned object stays open, so you are now responsible for closing it.
detach() is a method of text files (io.TextIOWrapper, returns the binary buffer) and buffered binary files (io.BufferedReader, BufferedWriter, BufferedRandom, returns the raw FileIO). Raw FileIO objects do not have it. No import is needed.
Syntax
Call it with no arguments and keep the returned object.
python
buffer = text_file.detach()
raw = buffer.detach()
Call
What it does
text_file.detach()
Returns the binary buffer, such as a BufferedReader.
binary_file.detach()
Returns the raw FileIO object.
text_file.read()
After detaching: raises ValueError.
Detach before reading: the text layer may already have read ahead, so bytes it buffered would be skipped by the returned object.
Method signatures
python
TextIOWrapper.detach() # -> the binary buffer (BufferedReader/Writer/Random)
BufferedReader.detach() # -> the raw FileIO (also BufferedWriter, BufferedRandom)
# FileIO has no detach()
Parameters
detach() takes no parameters.
Return Value
Return Value
Description
binary buffer
From a text file: the BufferedReader, BufferedWriter, or BufferedRandom it was wrapping, still open.
FileIO
From a buffered binary file: the raw file object, still open.
Python Examples
Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.
Example 1 — Read a Text File's Raw Bytes After detach()
Detach the buffer from a freshly opened text file and read the bytes directly.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "sensor.txt")
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write("temp=21\n")
f = open(path, encoding="utf-8")
buffer = f.detach()
print(type(f).__name__, "->", type(buffer).__name__)
with buffer:
print(buffer.read())
try:
f.read()
except ValueError:
print("the text wrapper is unusable after detach()")
Output
TextIOWrapper -> BufferedReader
b'temp=21\n'
the text wrapper is unusable after detach()
How It Works
Detach first. Nothing has been read through the text layer yet, so the buffer starts at byte 0.
Bytes out. The returned BufferedReader reads bytes, not str.
You own the buffer. The with buffer: block closes it, which also closes the file before the folder is removed.
Old wrapper is dead.f.read() raises ValueError because the wrapper no longer has a buffer.
Example 2 — Switch Encoding Mid-File by Rewrapping the Buffer
Write one UTF-8 line, detach, and continue writing through a new Latin-1 text wrapper.
python
import io
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "labels.txt")
f = open(path, "w", encoding="utf-8", newline="\n")
f.write("utf-8 part\n")
buffer = f.detach()
print(type(buffer).__name__)
with io.TextIOWrapper(buffer, encoding="latin-1", newline="\n") as latin:
latin.write("caf\u00e9\n")
with open(path, "rb") as check:
print(check.read())
Output
BufferedWriter
b'utf-8 part\ncaf\xe9\n'
How It Works
Flushed on detach. The UTF-8 line was still buffered in the text layer; detach() pushes it down before returning the BufferedWriter.
New wrapper, new encoding.io.TextIOWrapper(buffer, encoding="latin-1") continues writing to the same file.
One byte for e-acute. Latin-1 stores é as the single byte \xe9, unlike UTF-8's two bytes.
Wrapper closes the chain. Leaving the with block closes the new wrapper, its buffer, and the file.
Example 3 — Peel a Binary File Down to FileIO
Detach the raw layer from a BufferedReader, read from it, and confirm raw files cannot detach further.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "chunk.bin")
with open(path, "wb") as f:
f.write(b"\x01\x02\x03\x04")
buffered = open(path, "rb")
raw = buffered.detach()
print(type(buffered).__name__, "->", type(raw).__name__)
with raw:
print(raw.read(3), hasattr(raw, "detach"))
Output
BufferedReader -> FileIO
b'\x01\x02\x03' False
How It Works
Lowest layer. A buffered binary file detaches into the raw FileIO that talks to the operating system.
Unbuffered reads.raw.read(3) is a single system call; on this small regular file it returns all three requested bytes.
Bottom of the stack.FileIO has nothing beneath it, so it has no detach() method at all.
Frequently Asked Questions
On a text file it returns the binary buffer (BufferedReader, BufferedWriter, or BufferedRandom). On a buffered binary file it returns the raw FileIO object.
No. The detached object raises ValueError for reads, writes, and even the closed attribute. Use the object that detach() returned instead.
Yes. detach() does not close anything, so close the returned buffer or raw file yourself, or wrap it in a new TextIOWrapper and close that.
f.buffer gives you the binary layer while the text file stays usable. detach() hands the layer over and makes the text file unusable, so the two never fight over the position.
Use reconfigure() to change encoding, errors, or newline on Python 3.7+. Use detach() when you need the binary layer itself, for example to wrap it in a different kind of stream.