pathlib

#在拼接的时候,两边必须要有一边是Path对象
from pathlib import Path
'b'/ Path('c/d')
p1=('b' / Path('c/b'))
p1
WindowsPath('b/c/b')


p1.parts
('a', 'b', 'c', 'd', 'e', 'f', 'g')

p1 #repr
WindowsPath('a/b/c/d/e/f/g')

str(p1) #str
'a\\b\\c\\d\\e\\f\\g'

#取各个元素
p1.parts
('a', 'b', 'c', 'd', 'e', 'f', 'g')
#取目录
p1.parent.parent
WindowsPath('a/b/c/d/e')

#各种拼和打散
(p1.parent.parent / 'mysql.tar.gz').parts
('a', 'b', 'c', 'd', 'e', 'mysql.tar.gz')
p2.joinpath('123'/Path('ww'))
WindowsPath('a/b/c/d/e/123/ww')


p3=(p1.parent.parent / 'mysql.tar.gz')
p3
WindowsPath('a/b/c/d/e/mysql.tar.gz')

#取父名称,跟子文件名称,还有扩展名
p3.parent,p3.name,p3.suffix,p3.stem
(WindowsPath('a/b/c/d/e'), 'mysql.tar.gz', '.gz', 'mysql.tar')

#更换扩展名
p3.with_suffix('.xz')
WindowsPath('a/b/c/d/e/mysql.tar.xz')
p3.parent / 'mysql.ini'
WindowsPath('a/b/c/d/e/mysql.ini')
p3.with_name('mysql.zip')
WindowsPath('a/b/c/d/e/mysql.zip')
for x in p3.parents:
print(x)
a\b\c\d\e
a\b\c\d
a\b\c
a\b
a
.

p3.parents[0]
WindowsPath('a/b/c/d/e')
p1.home()
WindowsPath('C:/Users/polaris')
p1.cwd()
WindowsPath('C:/Users/polaris')
p2.exists()
False
p2.is_dir()
False


list(p3.parent.parent.iterdir())
[WindowsPath('a/b/c/d/e')]

posted @ 2022-09-19 11:21  红丿领巾  阅读(49)  评论(0)    收藏  举报