Path Operations Join And Resolve
Compose and normalize filesystem paths with pathlib so relative segments, parents, and safety checks read as object operations.
Code
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: FalseInside 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
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.