How can I access the filenames gathered by tf.data.Dataset.list_files?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
tf.data.Dataset.list_files() creates a dataset whose elements are file paths, not file contents. That means the filenames are already there as scalar string tensors; the main task is understanding how to inspect them, decode them, or carry them forward through your input pipeline.
Core Sections
What list_files Returns
At a high level, list_files turns a glob pattern into a dataset of path strings.
Typical output looks like a TensorFlow string tensor:
So the filename is not hidden. It is the dataset element itself.
Access Filenames in Eager Execution
If you are running in eager mode, convert each tensor to a Python string with .numpy(), then decode it.
That is the easiest way to inspect filenames during debugging or exploratory work.
You can also materialize the dataset with as_numpy_iterator():
Use the Filename Inside a Pipeline
A common pattern is to read the file content while still keeping the path available for labels, logging, or output naming.
Returning both values is often better than discarding the path immediately. It gives you traceability later in the pipeline.
Extract Just the Base Filename
If you only want cat.jpg instead of the full path, use TensorFlow string operations so the logic stays inside the graph-friendly pipeline.
For cross-platform code, tf.strings.regex_replace or preprocessing outside the pipeline may be safer than assuming a slash separator everywhere.
Build Labels From Filenames
Sometimes the filename itself contains the class label or identifier. You can derive labels directly from the path.
That pattern is common when directory names represent classes, such as cats/, dogs/, or cars/.
Another useful pattern is to keep the path all the way through batching so failed predictions can be traced back to source files later. That is especially helpful in evaluation code, dataset audits, and export jobs that need deterministic filename-to-output mapping.
That path-carrying approach also makes it much easier to log bad samples, copy specific files for manual review, or generate reports that join model outputs back to original filenames without rebuilding the dataset from scratch.
Common Pitfalls
- Expecting
list_filesto yield file contents instead of path tensors. - Using normal Python string methods inside a TensorFlow
mapfunction. - Forgetting that
list_filesshuffles by default unless you setshuffle=False. - Converting tensors to Python strings too early in a production input pipeline.
- Dropping the path immediately even though later stages need filenames for labels, logging, or exports.
Summary
- '
tf.data.Dataset.list_files()produces a dataset of filename tensors.' - In eager mode, use
.numpy().decode("utf-8")oras_numpy_iterator()to inspect paths. - Keep the path in the pipeline if you need traceability, labels, or output naming.
- Use TensorFlow string operations inside
mapfunctions instead of Python string methods. - Set
shuffle=Falsewhen deterministic filename order matters.
Related reading
- How can I add an optional input to a graph in TensorFlow?
- How can I add labels to TensorBoard Images?
- How can I assign a class_weight in Keras in a simple way?
- How can I build libtensorflow.so for the Tensorflow Rust bindings without SSE?
- How can I apply reinforcement learning to continuous action spaces?
- How can I apply reinforcement learning to continuous action spaces?
- How can I add new keys to a dictionary?
- How can I add to List? extends Number data structures?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.