对python3中pathlib库的Path类的使用详解

原文连接   https://www.jb51.net/article/148789.htm

1.调用库

?
1
from pathlib import

2.创建Path对象

?
1
2
3
4
5
6
7
p = Path( 'D:/python/1.py' )
print (p)
 
#可以这么使用,相当于os.path.join()
p1 = Path( 'D:/python' )
p2 = p1 / '123'
print (p2)

结果

?
1
2
D:\python\ 1.py
D:\python\ 123

3.Path.cwd()

获取当前路径

?
1
2
path = Path.cwd()
print (path)

结果:

?
1
D:\python

4.Path.stat()

获取当前文件的信息

?
1
2
p = Path( '1.py' )
print (p.stat())

结果

?
1
os.stat_result(st_mode = 33206 , st_ino = 8444249301448143 , st_dev = 2561774433 , st_nlink = 1 , st_uid = 0 , st_gid = 0 , st_size = 4 , st_atime = 1525926554 , st_mtime = 1525926554 , st_ctime = 1525926554 )

5.Path.exists()

判断当前路径是否是文件或者文件夹

?
1
2
3
4
5
6
>>> Path( '.' ).exists()
True
>>> Path( '1.py' ).exists()
True
>>> Path( '2.py' ).exists()
False

6.Path.glob(pattern)与Path.rglob(pattern)

Path.glob(pattern):获取路径下的所有符合pattern的文件,返回一个generator

目录下的文件如下:

python3 pathlib库的Path类的使用

以下是获取该目录下所有py文件的路径:

?
1
2
3
4
path = Path.cwd()
pys = path.glob( '*.py' ) #pys是经过yield产生的迭代器
for py in pys:
   print (py)

结果:

?
1
2
3
4
C:\python\ 1.py
C:\python\ 11.py
C:\python\ 1111.py
C:\python\ 11111.py

Path.rglob(pattern):与上面类似,只不过是返回路径中所有子文件夹的符合pattern的文件。

7.Path.is_dir()与Path.is_file()

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Path.is_dir()判断该路径是否是文件夹
Path.is_file()判断该路径是否是文件
 
print ( 'p1:' )
p1 = Path( 'D:/python' )
print (p1.is_dir())
print (p1.is_file())
 
print ( 'p2:' )
p2 = Path( 'D:/python/1.py' )
print (p2.is_dir())
print (p2.is_file())
 
#当路径不存在时也会返回Fasle
print ( 'wrong path:' )
print (Path( 'D:/NoneExistsPath' ).is_dir())
print (Path( 'D:/NoneExistsPath' ).is_file())

结果

?
1
2
3
4
5
6
7
8
9
p1:
True
False
p2:
False
True
wrong path:
False
False

8.Path.iterdir()

当path为文件夹时,通过yield产生path文件夹下的所有文件、文件夹路径的迭代器

?
1
2
3
p = Path.cwd()
for i in p.iterdir():
   print (i)

结果

?
1
2
3
4
5
D:\python\ 1.py
D:\python\ 11.py
D:\python\ 1111.py
D:\python\ 11111.py
D:\python\ dir

9.Path.mkdir(mode=0o777,parents=Fasle)

根据路径创建文件夹

parents=True时,会依次创建路径中间缺少的文件夹

?
1
2
3
4
5
p_new = p / 'new_dir'
p_new.mkdir()
 
p_news = p / 'new_dirs/new_dir'
p_news.mkdir(parents = True )

结果

python3 pathlib库的Path类的使用

10.Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

类似于open()函数

11.Path.rename(target)

当target是string时,重命名文件或文件夹

当target是Path时,重命名并移动文件或文件夹

?
1
2
3
4
5
6
p1 = Path( '1.py' )
p1.rename( 'new_name.py' )
 
p2 = Path( '11.py' )
target = Path( 'new_dir/new_name.py' )
p2.rename(target)

结果

python3 pathlib库的Path类的使用

12.Path.replace(target)

重命名当前文件或文件夹,如果target所指示的文件或文件夹已存在,则覆盖原文件

13.Path.parent(),Path.parents()

parent获取path的上级路径,parents获取path的所有上级路径

14.Path.is_absolute()

判断path是否是绝对路径

15.Path.match(pattern)

判断path是否满足pattern

16.Path.rmdir()

当path为空文件夹的时候,删除该文件夹

17.Path.name

获取path文件名

18.Path.suffix

获取path文件后缀

以上这篇对python3中pathlib库的Path类的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

猜你喜欢

转载自www.cnblogs.com/qinhan/p/10102377.html