In [19]: Path().resolve()
Out[19]: PosixPath('/home/python/steven/projects/web')
In [4]: Path().absolute()
Out[4]: PosixPath('/home/python/steven/projects/web')
exists()目录或文件是否存在
In [8]: Path('/etc/test').exists()
Out[8]: False
rmdir()删除空目录。没有提供判断目录为空的方法
In [10]: Path('/tmp/test').rmdir()
In [11]: ll /tmp
total 0# 如果目录有文件,会报错
OSError: [Errno 39] Directory not empty: '/tmp/test'
touch(mode=0o666,exist_ok=True)创建一个文件
In [29]: Path('/tmp/1.sh').touch()
In [30]: ll /tmp
total 1
-rw-rw-r-- 1 python 0 Apr 2508:391.sh
as_uri()将路径返回成URI,例如’file:///etc/passwd’
In [31]: Path('/tmp').as_uri()
Out[31]: 'file:///tmp'
In [32]: Path('/tmp/test').mkdir()
In [33]: ll /tmp
total 1
drwxrwxr-x 2 python 4096 Apr 2508:53 test/
In [37]: Path('/tmp/a/b/c/d').mkdir(parents=True)
In [39]: Path('/tmp/a/b/c/d').mkdir(parents=True, exist_ok=True)
# 遍历,并判断文件类型,如果是目录是否可以判断其是否为空?from pathlib import Path
p = Path()
p /= 'a/b/c/d/readme.txt'
p.mkdir(parents=True, exist_ok=True)
for x in p.parents[len(p.parents)-1].iterdir():
"""
p.parents[len(p.parents)-1],获取的是当前文件夹的位置, readme.txt的第4层父是. 为了获取.的位置
p.parents[len(p.parents)-1].iterdir(),迭代生成器
"""
print(x, end='\t')
if x.is_dir(): # 判断是会否是文件夹
flag = Falsefor _ in x.iterdir(): # 判断里面是否有文件夹
flag = Truebreak# for 循环是否可以使用else子句
print('dir', 'Not Empty'if flag else'Empyt', sep='\t')
elif x.is_file(): # 判断是否是文件
print('file')
else:
print('other file')
~~~~~~~~~~~~~~~~~~~~
Untitled.ipynb file
a dir Not Empty
b dir Empyt
Python10Training dir Not Empty
通配符
glob(pattern)通配给定的模式
rglob(pattern)通配给定的模式,递归目录,返回一个生成器
In [4]: list(Path().glob('test*')) # 返回当前对象下的test开头的文件
Out[4]:
[PosixPath('test.b'),
PosixPath('test1.py'),
PosixPath('test.a'),
PosixPath('test.py')]
In [5]: list(Path().glob('**/*.py')) #递归所有目录,等同rglob
Out[5]: [PosixPath('test1.py'), PosixPath('test.py')]
In [6]: g = Path().rglob('*.py') # 生成器
In [7]: next(g)
Out[7]: PosixPath('test1.py')
In [8]: next(g)
Out[8]: PosixPath('test.py')
In [4]: p = Path('my_binary_file')
In [5]: p.write_bytes(b'Binary file contents')
Out[5]: 20
In [6]: p.read_bytes()
Out[6]: b'Binary file contents'
In [7]: p = Path('my_test_file')
In [8]: p.write_text('Text file contents')
Out[8]: 18
In [9]: p.read_text()
Out[9]: 'Text file contents'
from pathlib import Path
p = Path('test.py')
p.write_text('hello python')
print(p.read_text())
with p.open() as f:
print(f.read(5))
~~~~~~~~~~~~~~~~~~~~~~~~~
hello python
hello