file management
directory handling
programming
filenames
path extraction

Get filenames without path of a specific directory

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you want only filenames from a directory, the cleanest solution is to ask the filesystem API for directory entries and then read each entry’s name property. The key is to avoid building full paths first and stripping them later unless your language or tool gives you no better option.

Use the Directory API, Not String Slicing

Treating paths as plain strings is error-prone because separators differ across operating systems and special cases such as trailing slashes or Unicode filenames can surprise you. It is better to use a filesystem API that already understands what a filename is.

In Python, pathlib makes this very direct:

python
1from pathlib import Path
2
3
4def filenames(directory: str) -> list[str]:
5    return [entry.name for entry in Path(directory).iterdir() if entry.is_file()]
6
7
8print(filenames("/tmp"))

entry.name gives you only the final filename component, not the full path.

Use os.scandir for Large Directories

If performance matters, os.scandir is often a good choice because it yields directory entries with cheap metadata access:

python
1import os
2
3
4def filenames_scandir(directory: str) -> list[str]:
5    with os.scandir(directory) as entries:
6        return [entry.name for entry in entries if entry.is_file()]
7
8
9print(filenames_scandir("/tmp"))

This approach is efficient and avoids calling os.path.basename on a list of full paths you never needed in the first place.

If You Already Have Full Paths, Use a Path Helper

Sometimes the upstream code already gave you full paths. In that case, convert them with a proper path utility instead of manual string splitting:

python
1import os
2
3paths = [
4    "/var/log/system.log",
5    "/var/log/app.log",
6]
7
8names = [os.path.basename(path) for path in paths]
9print(names)

This is a good fallback pattern, but it is still a second-best option compared with asking the directory iterator for names directly.

Shell Example

On Unix-like systems, the shell can do the same job. find is a better example than ls because it is easier to control:

bash
find /tmp -maxdepth 1 -type f -printf '%f\n'

%f prints only the final filename component. This is usually safer than parsing the output of ls, which is meant for humans rather than stable scripting.

Decide Whether You Want Files, Directories, or Both

A directory listing can include regular files, directories, symbolic links, sockets, and more. The question “get filenames” often really means “get the names of regular files only,” but not always.

That is why filtering matters. In the Python examples above, entry.is_file() excludes directories. If you want every entry name instead, drop that condition:

python
1from pathlib import Path
2
3all_names = [entry.name for entry in Path("/tmp").iterdir()]
4print(all_names)

The correct answer depends on what the caller means by “filenames.”

Hidden Files and Sorting

Many APIs include hidden files by default. If your use case should exclude names beginning with a dot, add that explicitly:

python
1from pathlib import Path
2
3visible = [
4    entry.name
5    for entry in Path("/tmp").iterdir()
6    if entry.is_file() and not entry.name.startswith(".")
7]
8
9print(sorted(visible))

Sorting is another separate concern. Filesystem iteration order is not guaranteed to be alphabetic, so sort the result if stable ordering matters.

Common Pitfalls

The most common mistake is parsing paths manually with string splitting. That works until a path format, platform, or edge case differs from what you assumed.

Another pitfall is forgetting to filter entry types. Directory APIs can return more than regular files, so be explicit about whether directories and symlinks should be included.

It is also easy to assume the returned order is stable. Many directory iteration APIs do not guarantee sort order, so call sorted if the output needs to be predictable.

Finally, avoid parsing ls output in scripts. Purpose-built filesystem APIs and structured command output are safer and easier to maintain.

Summary

  • Use a filesystem API such as pathlib or os.scandir instead of string slicing.
  • Read the entry name directly when iterating a directory.
  • Use os.path.basename only when full paths already exist.
  • Filter for files, directories, or visible entries explicitly based on the real requirement.
  • Sort the result yourself if the caller needs a stable order.

Course illustration
Course illustration

All Rights Reserved.