Skip to main content

How to Write a File in TensorFlow with tf.io.write_file

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

tf.io.write_file is the other half of tf.io.read_file: it writes text or bytes to a file, from Python or from inside a TensorFlow graph. It's how TensorFlow code saves an encoded image or a short report. This guide writes a greeting into a folder that doesn't exist yet, in TensorFlow 2.22.0, and reads it back.

Syntax​

Syntax
tf.io.write_file(<path>, <contents>)
PartWhat it means
<path>Where to write, as text or a string tensor. Missing folders are created
<contents>What to write: text, bytes or a string tensor, such as an encoded JPEG

The tf.io.write_file API page: it "Writes contents to the file at input filename. Creates the file and recursively creates directory if it does not exist." Both arguments are string tensors: the file name and "The content to be written to the output file."

The Example​

A one-line greeting written to output/greeting.txt. The output folder doesn't exist before the script runs.

Prerequisites​

  • A uv project with TensorFlow. This guide uses TensorFlow 2.22.0 on Python 3.14.10, with uv 0.13.10.

Step 1: Write the Script​

write_demo.py
import tensorflow as tf

tf.io.write_file("output/greeting.txt", "Hello from TensorFlow\n")

print(tf.io.read_file("output/greeting.txt"))

The write_demo.py script in a macOS-style code window: tf.io.write_file writes Hello from TensorFlow and a line break to output/greeting.txt, then tf.io.read_file reads it back and prints it.

The script writes the file, then reads it back with tf.io.read_file to show what's in it.

Step 2: Run It​

Terminal
uv run python write_demo.py
Output
tf.Tensor(b'Hello from TensorFlow\n', shape=(), dtype=string)

The terminal after uv run python write_demo.py: the file read back as a string tensor holding b'Hello from TensorFlow\n'.

The file holds exactly what was written, line break included. tf.io.write_file created the output folder first, so the project now has output/greeting.txt. The command works unchanged in PowerShell.

The first run in a new environment is slow, while TensorFlow loads for the first time.

Common Mistakes​

MistakeWhat happensDo this instead
Passing a pathlib.PathValueError: Attempt to convert a value (PosixPath('output/greeting.txt')) with an unsupported type (<class 'pathlib.PosixPath'>) to a Tensor.Wrap it in str(): tf.io.write_file(str(Path("output") / "greeting.txt"), ...) worked. Fixed: ValueError: Attempt to convert a value (PosixPath(…)) with an unsupported type to a Tensor explains why
Writing a tensor of numberstf.io.write_file(path, tf.constant([1, 2, 3])) stopped with ValueError: Tensor conversion requested dtype string for Tensor with dtype int32. The contents must be a string tensorTurn the tensor into bytes first, as the FAQ below shows
Writing to a file that already existsThe old contents are replaced without a warning: after writing first and then second, the file held b'second'Use a new name for each file you want to keep
Reading the file back inside the same tf.functionThe read can run before the write: NotFoundError: Graph execution error with [[{{node ReadFile}}]]Make the read wait for the write with tf.control_dependencies. Fixed: NotFoundError: Graph execution error … [[{{node ReadFile}}]] After tf.io.write_file in tf.function shows how. I reported it to TensorFlow as issue #131029

FAQ​

How do I save a tensor of numbers to a file?​

Turn it into bytes with tf.io.serialize_tensor, write those, and turn them back with tf.io.parse_tensor, giving the type: tf.io.parse_tensor(tf.io.read_file(path), tf.int32) returned tf.Tensor([1 2 3], shape=(3,), dtype=int32). For an image, encode it as a JPEG with tf.io.encode_jpeg instead.

Why use tf.io.write_file and not Python's open()?​

In ordinary Python code, both work. Inside a tf.function, only tf.io.write_file does: there the file name is a tensor that doesn't have its value yet. tf.io.write_file(name, text) wrote the file, while open(name, "w") stopped with TypeError: expected str, bytes or os.PathLike object, not SymbolicTensor.

Conclusion​

tf.io.write_file wrote a greeting to output/greeting.txt, creating the output folder on the way, and tf.io.read_file read back exactly the same bytes. Its path must be text, not a Path, its contents must be a string tensor, and it replaces a file that already exists.

Additional Resources​