List files

2 snippets across 2 stacks - Bash & Linux, Python

SHBash & Linux

List Directory Contents

SH · Navigation & Files
Syntax
ls [options] [directory]
Example
ls -la /etc
ls -lhS ~/Downloads
ls -lt --color=auto
Output
drwxr-xr-x  5 deploy staff  160 Mar 12 09:14 config
-rw-r--r--  1 deploy staff 2.4K Mar 11 18:30 app.js

Note -l for long format, -a includes hidden files (dotfiles), -h for human-readable sizes, -S sorts by size, -t sorts by modification time (newest first), -R lists recursively.

PYPython

Finding Files with Glob

PY · File I/O
Syntax
Path(dir).glob(pattern)
Path(dir).rglob(pattern)
Example
from pathlib import Path

# All Python files in current directory
for py_file in Path(".").glob("*.py"):
    print(py_file.name)

# Recursive search
all_json = list(Path(".").rglob("*.json"))
print(f"Found {len(all_json)} JSON files")

Note glob() searches one level. rglob() searches recursively through all subdirectories. Both return Path objects.

Frequently asked questions

How do you list files?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "List Directory Contents" snippet in Bash & Linux uses `ls [options] [directory]`.
Which command does the Bash & Linux example use?
The "List Directory Contents" snippet uses `ls [options] [directory]`, from the Navigation & Files section of the Bash & Linux cheat sheet.
Which stacks cover "list files" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "List Directory Contents": -l for long format, -a includes hidden files (dotfiles), -h for human-readable sizes, -S sorts by size, -t sorts by modification time (newest first), -R lists recursively.