Skip to main content

fs/deepestdir

1#!/usr/bin/env python3
2"""
3Usage: deepestdir [<ROOT>]
5Prints the path to the deepest directory under the given root. If no root
6is given, the current directory is used. If there are multiple directories
7at the same depth, only one is printed.
8"""
10import functools
11import os
12import sys
15def get_dir_paths_under(root):
16 """Generates the paths to every directory under ``root``."""
17 for dirpath, dirnames, _ in os.walk(root):
18 for d in dirnames:
19 yield os.path.join(dirpath, d)
22@functools.cache
23def directory_depth(d):
24 """Returns the depth of a directory in the filesystem."""
25 if os.path.dirname(d) == d:
26 return 0
27 else:
28 return 1 + directory_depth(os.path.dirname(d))
31if __name__ == "__main__":
32 try:
33 root = sys.argv[1]
34 except IndexError:
35 root = "."
37 print(max(get_dir_paths_under(root), key=directory_depth))