原文: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. 二级缓存EhCache在几种应用技术的配置方法和步骤总结

    一:Spring和Ehcache缓存集成 业务问题:如果仓库不经常变动,大量进出库,总是需要查询仓库列表 (列表重复) ,使用缓存优化 ! 阅读spring规范29章节 第一步: 导入ehcache的 ...

  2. spoj high

    matrixtree定理裸体,学了行列式的n^3解法,(应该是能应用于所有行列式): 代码是参考某篇题解的... #include<iostream> #include<cstrin ...

  3. 20169207《Linux内核原理与分析》第八周作业

    本章的作业依旧包括两部分,1.阅读学习教材「Linux内核设计与实现 (Linux Kernel Development)」第教材第11,12章. 2.学习MOOC「Linux内核分析」第六讲「进程的 ...

  4. (完全背包)Writing Code -- Codeforce 544C

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=99951#problem/C  (zznu14) Writing Code  Writin ...

  5. 【python-字典】判断python字典中key是否存在的

    一般有两种通用做法: 第一种方法:使用自带函数实现: 在python的字典的属性方法里面有一个has_key()方法: #生成一个字典 d = {'name':Tom, 'age':10, 'Tel' ...

  6. 网络timeout区分

    ConnectTimeout 连接建立时间,三次握手完成时间 SocketTimeout 数据传输过程中数据包之间间隔的最大时间 下面重点说下SocketTimeout,比如有如下图所示的http请求 ...

  7. Scala界面事件处理编程实战详解.

    今天学习了一个Scala界面事件处理编程,让我们从代码出发. import scala.swing._import scala.swing.event._ object GUI_Panel exten ...

  8. Stringbuffer与substring

    1. Stringbuffer 有append()方法 Stringbuffer 其实是动态字符串数组 append()是往动态字符串数组添加,跟“xxxx”+“yyyy”相当那个‘+’号 跟Stri ...

  9. DXP中插入LOGO字体方法(2)

    利用字体制作软件font creator program 4.1 1.文件-->新建 2.右键---->属性 3.去掉黑框和黑底,删除即可! 4.选 工具--->导入图像,载入字体图 ...

  10. golang简单实现jwt验证(beego、xorm、jwt)

    程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息. app.conf文件内容(可以用个beego直接读取里面的内容)写的是一个jwt的se ...