Simplify a Unix-style absolute path. Args: path: An absolute file path string. Returns: The simplified canonical path. Examples: >>> simplify_path("/home/") '/home' >>> simplify_path("/a/./b/../../c/") '/c'
(path: str)
| 15 | |
| 16 | |
| 17 | def simplify_path(path: str) -> str: |
| 18 | """Simplify a Unix-style absolute path. |
| 19 | |
| 20 | Args: |
| 21 | path: An absolute file path string. |
| 22 | |
| 23 | Returns: |
| 24 | The simplified canonical path. |
| 25 | |
| 26 | Examples: |
| 27 | >>> simplify_path("/home/") |
| 28 | '/home' |
| 29 | >>> simplify_path("/a/./b/../../c/") |
| 30 | '/c' |
| 31 | """ |
| 32 | skip = {"..", ".", ""} |
| 33 | stack: list[str] = [] |
| 34 | tokens = path.split("/") |
| 35 | for token in tokens: |
| 36 | if token == "..": |
| 37 | if stack: |
| 38 | stack.pop() |
| 39 | elif token not in skip: |
| 40 | stack.append(token) |
| 41 | return "/" + "/".join(stack) |