原文:https://xin053.github.io/2016/07/03/pathlib%E8%B7%AF%E5%BE%84%E5%BA%93%E4%BD%BF%E7%94%A8%E8%AF%A6%E8%A7%A3/

pathlib简介

pathlib库在python 3.4以后已经成为标准库,基本上可以代替os.path来处理路径。它采用完全面对对象的编程方式。

总共有6个类用来处理路径,大体可以分为两类:

  1. pure paths 单纯的路径计算操作而没有IO功能
  2. concrete paths 路经计算操作和IO功能

这6个类的继承关系如下:

可以看到PurePath是所有类的基类,我们重点要掌握PurePathPath这两个类,在Windows平台下路径对象会有Windows前缀,Unix平台上路径对象会有Posix前缀。

基本使用

列出所有子目录

1
2
3
4
5
6
7
>>> import pathlib
>>> p = pathlib.Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[WindowsPath('.git'), WindowsPath('.idea'), WindowsPath('.vscode'),
WindowsPath('1_函数参数'), WindowsPath('2_生成器'), WindowsPath('3_常用函数'),
WindowsPath('4_装饰器), WindowsPath('5_常用模块')]
# 在linux环境下,上述的WindowsPath都会变为PosixPath

列出指定类型的文件

1
list(p.glob('**/*.py'))

路径拼接

可以使用/符号来拼接路径

1
2
3
4
>>> p = pathlib.Path(r'F:\cookies\python')
>>> q = p / 'learnPython'
>>> print(q)
F:\cookies\python\learnPython

查询属性

1
2
3
4
>>> q.exists()
True
>>> q.is_dir()
True

打开文件

1
2
3
4
>>> q = q / "hello_world.py"
>>> with q.open() as f:
>>> print(f.readline())
#!/usr/bin/env python

Pure paths

产生Pure paths的三种方式

class pathlib.PurePath(*pathsegments)

1
2
3
>>> PurePath('setup.py')
PurePosixPath('setup.py') # Running on a Unix machine
PureWindowsPath('setup.py') # Running on a Windows machine
1
2
3
4
>>> PurePath('foo', 'some/path', 'bar')
PureWindowsPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PureWindowsPath('foo/bar')

如果参数为空,则默认指定当前文件夹

1
2
>>> PurePath()
PureWindowsPath('.')

当同时指定多个绝对路径,则使用最后一个

1
2
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

在Windows平台上,参数路径上如果有\或者/,则使用之前设置的盘符

1
2
>>> PureWindowsPath('F:\cookies\python\learnPython','\game')
PureWindowsPath('F:/game')

class pathlib.PurePosixPath(*pathsegments)

1
2
>>> PurePosixPath('/etc')
PurePosixPath('/etc')

class pathlib.PureWindowsPath(*pathsegments)

1
2
>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')

Path计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True
>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: PureWindowsPath() < PurePosixPath()

str() 和 bytes()

1
2
3
4
5
6
7
8
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
>>> bytes(p)
b'/etc'

常用属性和方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PurePosixPath('/etc').root
'/'
 
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
 
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
 
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
 
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
 
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
 
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
 
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
 
>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False
 
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 694, in relative_to
.format(str(self), str(formatted)))
ValueError: '/etc/passwd' does not start with '/usr'
 
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
 
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')

Concrete paths

产生Concrete paths的三种方式

class pathlib.Path(*pathsegments)

1
2
3
>>> Path('setup.py')
PosixPath('setup.py') # Running on a Unix machine
WindowsPath('setup.py') # Running on a Windows machine

class pathlib.PosixPath(*pathsegments)

1
2
>>> PosixPath('/etc')
PosixPath('/etc')

class pathlib.WindowsPath(*pathsegments)

1
2
>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')

常用方法

cwd()设置path对象为当前路径

1
2
>>> Path.cwd()
WindowsPath('D:/Python 3.5')

stat()获取文件或目录属性

1
2
3
>>> p = Path('setup.py')
>>> p.stat().st_size
956

chmod()Unix系统修改文件或目录权限

exists()判断文件或目录是否存在

1
2
3
4
5
6
7
8
9
>>> from pathlib import *
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False

glob()列举文件

1
2
3
4
5
6
7
8
9
10
11
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]
>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
PosixPath('docs/conf.py'),
PosixPath('pathlib.py'),
PosixPath('setup.py'),
PosixPath('test_pathlib.py')]
# The "**" pattern means "this directory and all subdirectories, recursively"

is_dir()判断是否是目录

is_file()判断是否是文件

is_symlink()判断是否是链接文件

iterdir()如果path指向一个目录,则返回该目录下所有内容的生成器

mkdir(mode=0o777, parents=False)创建目录

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)打开文件

owner()获取文件所有者

rename(target)修改名称

1
2
3
4
5
6
7
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
>>> target.open().read()
'some text'

resolve()Make the path absolute, resolving any symlinks. A new path object is returned

1
2
3
4
5
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')

rmdir()删除目录,目录必须为空

touch(mode=0o777, exist_ok=True)创建空文件

(转)pathlib路径库使用详解的更多相关文章

  1. STC8H开发(二): 在Linux VSCode中配置和使用FwLib_STC8封装库(图文详解)

    目录 STC8H开发(一): 在Keil5中配置和使用FwLib_STC8封装库(图文详解) STC8H开发(二): 在Linux VSCode中配置和使用FwLib_STC8封装库(图文详解) 前面 ...

  2. Python爬虫之selenium库使用详解

    Python爬虫之selenium库使用详解 本章内容如下: 什么是Selenium selenium基本使用 声明浏览器对象 访问页面 查找元素 多个元素查找 元素交互操作 交互动作 执行JavaS ...

  3. STC8H开发(一): 在Keil5中配置和使用FwLib_STC8封装库(图文详解)

    介绍 FwLib_STC8 是一个针对STC8G, STC8H系列MCU的C语言封装库, 适用于基于这些MCU的快速原型验证. 项目地址: Gitee FwLib_STC8 镜像地址: GitHub ...

  4. JNI_Android项目中调用.so动态库实现详解

    转自:http://www.yxkfw.com/?p=7223 1. 在Eclipse中创建项目:TestJNI 2. 新创建一个class:TestJNI.java package com.wwj. ...

  5. JNI_Android项目中调用.so动态库实现详解【转】

    转自 http://www.cnblogs.com/sevenyuan/p/4202759.html 1. 在Eclipse中创建项目:TestJNI 2. 新创建一个class:TestJNI.ja ...

  6. CREATE DATABASE建库语句详解

    原创地址:http://blog.csdn.net/guguda2008/article/details/5716939 一个完整的建库语句是类似这样的: IF DB_ID('TEST') IS NO ...

  7. Linux 库文件详解

    转自: http://www.cppblog.com/deane/articles/165216.html http://blog.sciencenet.cn/blog-1225851-904348. ...

  8. (笔记)Linux下的静态库和动态库使用详解

    库从本质上来说是一种可执行代码的二进制格式,可以被载入内存中执行.库分静态库和动态库两种. 一.静态库和动态库的区别 1. 静态函数库 这类库的名字一般是libxxx.a:利用静态函数库编译成的文件比 ...

  9. 深入探讨Linux静态库与动态库的详解(转)

    2.生成动态库并使用 linux下编译时通过 -shared 参数可以生成动态库(.so)文件,如下 库从本质上来说是一种可执行代码的二进制格式,可以被载入内存中执行.库分静态库和动态库两种. 一.静 ...

随机推荐

  1. GAME PROGRAMM

    SetConsoleTextAttribute consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE); GetStdHandle(nStdHandle)//是返回 ...

  2. 更改Ubuntu默认python版本的两种方法python-> Anaconda

    当你安装 Debian Linux 时,安装过程有可能同时为你提供多个可用的 Python 版本,因此系统中会存在多个 Python 的可执行二进制文件.一般Ubuntu默认的Python版本都为2. ...

  3. java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory的解决办法

    Tomcat7早就出来正式版,但是一直都没有用过,尤其是针对于我还一直在用Myeclipse6.5的人来说,它在配置tomcat的时候没有tomcat7的选项,所以就报了错误信息. java.lang ...

  4. 2-具体学习Github---init add commit log diff

    1.安装: 首先找到git的官网,内部有下载链接. 也可以用下面的,我的是win7的64位系统: 可以在此处下载:Git-2.13.0-64-bit.exe链接:http://pan.baidu.co ...

  5. 第22章:MongoDB-聚合操作--聚合管道--$out

    ①$out $out:利用此操作可以将查询结果输出到指定的集合里面. ②范例:将投影的结果输出到集合里

  6. 第05章:MongoDB-CRUD操作--数据库

    ①显示现有的数据库 命令:show dbs 或者databases; ②显示当前的数据库 命令:db ③使用|创建数据库 命令:use 数据库名称   如果数据库不存在,则创建数据库,否则切换到指定数 ...

  7. How to temporally disable IDE tools (load manually)

    It is possible to prevent the IDE Tools from being loaded automatically when starting Visual Studio. ...

  8. C#-VS SQLServer数据库编程-摘

    ado.net 通用类对象.在本地内存暂存数据 托管类对象.让本地通用类对象连接数据库,让本地通用类对象和数据库同步 连接数据库 new connection(connectstring) comma ...

  9. (转)JDK安装配置教程

    转自:http://jingyan.baidu.com/article/bea41d435bc695b4c41be648.html JDK作为JAVA开发的环境,不管是做JAVA开发的学生,还是做安卓 ...

  10. 20169207《Linux内核原理及分析》第十二周作业

    本周选做的信息安全实验为Python实现Zip文件的暴力破解 实验预备: 这次实验我们需要用到的库为zipfile.下来我们先来了解一下这个模块. 首先我们的重点是对zip文件的操作,而zipfile ...