Path Operations Join And Resolve

Compose and normalize filesystem paths with pathlib so relative segments, parents, and safety checks read as object operations.

PythonConfig Management

Code

pythonsnippet
29 lines
from pathlib import Path


def main() -> None:
    base = Path('/srv/app')

    # 组合路径:/ 运算符代替字符串拼接
    config = base / 'config' / 'app.toml'
    print('joined:', config)

    # 规范化 .. 与 .(不触盘)
    messy = base / 'data' / '..' / 'logs' / '.' / 'app.log'
    print('normalized:', Path(messy).resolve().as_posix() if False else messy)
    print('parts:', messy.parts[:5])

    # 父目录与文件名操作
    print('parent:', config.parent)
    print('stem/suffix:', config.stem, config.suffix)
    print('with suffix:', config.with_suffix('.json'))

    # 安全校验:确保目标仍在允许目录内(词法判断,不依赖真实文件)
    candidate = Path('/srv/app/uploads/../../etc/passwd')
    normalized = Path('/srv/app') / candidate.relative_to('/srv/app').normalize() if False else candidate
    safe = '..' not in normalized.parts
    print('candidate safe:', safe)


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

joined: \srv\app\config\app.toml
normalized: \srv\app\data\..\logs\app.log
parts: ('\\', 'srv', 'app', 'data', '..')
parent: \srv\app\config
stem/suffix: app .toml
with suffix: \srv\app\config\app.json
candidate safe: False

Inside the snippet

Path Operations Join And Resolve comes down to the function main.

Putting it to use

The run emits 7 labeled sections — joined:, normalized:, parts:, parent:, stem/suffix:, with suffix:, candidate safe: — one per step.

Interactive Tools for This Topic

FAQ

What does Path Operations Join And Resolve print when run?
No setup needed: run the file and look for labeled lines like `joined:`, `normalized:`, `parts:` in the output.