用了很久的os.path,今天发现竟然还有这么好用的库,记录下来以便使用。
1.调用库
1
|
|
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
目录下的文件如下:
以下是获取该目录下所有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)
|
结果
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)
|
结果
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类的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.****.net/AManFromEarth/article/details/80265843