Python路径操作
路径操作
path模块
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 /
Path类
从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
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)
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16