首页 > 其他分享 >Pythin - pathlib

Pythin - pathlib

时间:2022-11-12 10:23:49浏览次数:46  
标签:obj parent pathlib test print Path Pythin type

简介

跨平台,python 内置

  • PurePath:处理路径字符串
  • Path: 处理文件系统的真实路径

获取功能

# 将当前文件构建为Path对象
path_obj = Path(__file__)
print(f'path_obj => {path_obj}, type => {type(path_obj)}')
# out:path_obj => E:\PyProject\studentManage\test\test_pathlib.py, type => <class 'pathlib.WindowsPath'>

# 获取绝对路径, 推荐使用resolve,会做一些路径标准化的操作
resolve = path_obj.resolve()
absolute = path_obj.absolute()
print(f'resolve => {resolve},type => {type(resolve)}')
# resolve => E:\PyProject\studentManage\test\test_pathlib.py,type => <class 'pathlib.WindowsPath'>
print(f'absolute => {absolute}, type => {type(absolute)}')
# absolute => E:\PyProject\studentManage\test\test_pathlib.py, type => <class 'pathlib.WindowsPath'>


 # 获得上一层的文件对象
parent_obj = resolve.parent 
print(f'parent_obj => {parent_obj}, type => {type(path_obj)}')
# parent_obj => E:\PyProject\studentManage\test, type => <class 'pathlib.WindowsPath'>

 # 获得上一层的路径的文件名称
name_obj = parent_obj.name 
print(f'name_obj => {name_obj}, type => {type(name_obj)}')
# name_obj => test, type => <class 'str'>

print(parent_obj.parts)  # out: ('E:\\', 'PyProject', 'studentManage', 'test')
print(parent_obj.anchor)  # 返回根路径 out: E:\

路径拼接

print(Path.home()) # C:\Users\86158
print(Path.cwd()) # E:\PyProject\studentManage\test
print(Path(Path.home(),'Desktop'))  # C:\Users\86158\Desktop
print(Path.joinpath(Path.home(),'Desktop')) # C:\Users\86158\Desktop

标签:obj,parent,pathlib,test,print,Path,Pythin,type
From: https://www.cnblogs.com/czzz/p/16882802.html

相关文章