标签:获取路径 存在 network sysconfig sep 表达 int 操作符 xpath
from os import path #os 模块常用函数,os.path模块 p = path.join(‘/etc/‘,‘sysconfig‘,‘network‘) #拼接 print(type(p),p) print(path.exists(p)) #存在性判断 print(path.split(p)) #分隔 print(path.dirname(p),path.basename(p))#取路径和基名 print(path.abspath(‘‘),path.abspath(‘.‘)) #当前的绝对路径 print(‘*‘ * 30)
#打印父目录 p1 = path.abspath(__file__) #取当前文件名的对地路径 print(p1) while p1 != path.dirname(p1): p1 = path.dirname(p1) print(p1) #输出<class ‘str‘> /etc/sysconfig/network False (‘/etc/sysconfig‘, ‘network‘) /etc/sysconfig network /home/alren/PycharmProjects/Python /home/alren/PycharmProjects/Python ****************************** /home/alren/PycharmProjects/Python/file-operator.py /home/alren/PycharmProjects/Python /home/alren/PycharmProjects /home/alren /home /
从Python3.4开始提供了pathlib模快,使用Path类操作目录更为的方便
from pathlib import Path #从pathlib模快导入Path类 p1 = Path() p2 = Path(‘‘) p3 = Path(‘.‘) #Path()/Path(‘‘)/Path(‘.‘)都表示当前目录 print(p1) print(p2) print(p3) p = Path(‘a‘,‘b‘,‘c/d‘) #当前目录下的a/b/c/d print(p) p = Path(‘/etc/‘,Path(),Path(‘sysconfig‘),‘network/ifconfig‘) #Path拼接 print(p) #输出 . . . a/b/c/d /etc/sysconfig/network/ifconfig
Path对象 / Path对象
Path对象 / 字符串(str)
字符串 / Path对象
字符串 / 字符串 #错误表达式
from pathlib import Path p1 = Path() p2 = Path(‘‘) p3 = Path(‘.‘) print(p1) print(p2) print(p3) p = Path(‘a‘,‘b‘,‘c/d‘) print(p) p = Path(‘/etc/‘,Path(),Path(‘sysconfig‘),‘network/ifconfig‘) print(p) p1 = ‘/a‘ / Path(‘b‘,‘c/d‘) print(p1) p2 = Path(‘/a‘,‘b‘) / Path(‘c/d‘) print(p2) p3 = Path(‘/a/b/c‘) / ‘d‘ print(p3) p4 = ‘/a‘ / (‘b/c‘ / Path(‘d‘)) # ‘/a‘ / ‘b/c‘ / Path(‘d‘) 错误的表达式,str / str 不能使用/进行操作
print(p4)
joinpath(*other)在当前的Path路径上连接多个字符串返回新路径对象
from pathlib import Path p = Path() p = p / ‘a‘ p1 = ‘b‘ / p p2 = Path(‘c‘) p3 = p1 / p2 print(p1,p2,p3,sep=‘\n‘) print(p3.joinpath(‘d‘,‘e/f‘,Path(‘g/h‘))) #输出 b/a c b/a/c b/a/c/d/e/f/g/h
parts属性会返回目录各部分的元组
print(p3.parts) # (‘b‘, ‘a‘, ‘c‘)
str获取路径字符串
bytes获取路径字符串的bytes
print(str(p3),bytes(p3)) #b/a/c b‘b/a/c‘
parent目录的逻辑父目录
parents父目录惰性可迭代对象,索引0是直接的父目录
p = Path(‘/data/mysql/data/mysql.tar.gz‘) print(p.parent) #返回逻辑的父目录 print(p.parents)#返回一个惰性的可迭代对象 #输出 /data/mysql/data <PosixPath.parents>
遍历父目录
from pathlib import Path p = Path(‘/data/mysql/data/mysql.tar.gz‘) print(p.parent) # print(p.parents) for i in p.parents: print(i) from os import path p1 = path.join(‘/data/mysql/data/mysql.tar.gz‘) while p1 != path.dirname(p1): p1 = path.dirname(p1) print(p1)
标签:获取路径 存在 network sysconfig sep 表达 int 操作符 xpath
原文地址:https://www.cnblogs.com/alrenn/p/12811708.html