原文: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個類用來處理路徑,大體可以分為兩類:
- pure paths 單純的路徑計算操作而沒有IO功能
- concrete paths 路經計算操作和IO功能
這6個類的繼承關系如下:
可以看到PurePath
是所有類的基類,我們重點要掌握PurePath
和Path
這兩個類,在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
|
F:\cookies\python\learnPython
|
查詢屬性
1
2
3
4
|
True
True
|
打開文件
1
2
3
4
|
#!/usr/bin/env python
|
Pure paths
產生Pure paths的三種方式
class pathlib.PurePath(*pathsegments)
1
2
3
|
PurePosixPath(
'setup.py') # Running on a Unix machine
PureWindowsPath(
'setup.py') # Running on a Windows machine
|
1
2
3
4
|
PureWindowsPath(
'foo/some/path/bar')
PureWindowsPath(
'foo/bar')
|
如果參數為空,則默認指定當前文件夾
1
2
|
PureWindowsPath(
'.')
|
當同時指定多個絕對路徑,則使用最后一個
1
2
|
PureWindowsPath(
'd:bar')
|
在Windows平台上,參數路徑上如果有\
或者/
,則使用之前設置的盤符
1
2
|
PureWindowsPath(
'F:/game')
|
class pathlib.PurePosixPath(*pathsegments)
1
2
|
PurePosixPath(
'/etc')
|
class pathlib.PureWindowsPath(*pathsegments)
1
2
|
PureWindowsPath(
'c:/Program Files')
|
Path計算
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
False
True
True
True
False
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
|
'/etc'
'c:\\Program Files'
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
|
'c:'
'/'
PureWindowsPath(
'c:/foo/bar')
PureWindowsPath(
'c:/foo')
PureWindowsPath(
'c:/')
'setup.py'
''
'.py'
'.gz'
''
[
'.tar', '.gar']
[
'.tar', '.gz']
[]
'library.tar'
'library'
'library'
'c:\\windows'
'c:/windows'
'file:///etc/passwd'
'file:///c:/Windows'
True
True
False
PurePosixPath(
'etc/passwd')
PurePosixPath(
'passwd')
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'
PureWindowsPath(
'c:/Downloads/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
PureWindowsPath(
'c:/Downloads/pathlib.tar.bz2')
PureWindowsPath(
'README.txt')
|
Concrete paths
產生Concrete paths的三種方式
class pathlib.Path(*pathsegments)
1
2
3
|
PosixPath(
'setup.py') # Running on a Unix machine
WindowsPath(
'setup.py') # Running on a Windows machine
|
class pathlib.PosixPath(*pathsegments)
1
2
|
PosixPath(
'/etc')
|
class pathlib.WindowsPath(*pathsegments)
1
2
|
WindowsPath(
'c:/Program Files')
|
常用方法
cwd()
設置path對象為當前路徑
1
2
|
WindowsPath(
'D:/Python 3.5')
|
stat()
獲取文件或目錄屬性
1
2
3
|
956
|
chmod()
Unix系統修改文件或目錄權限
exists()
判斷文件或目錄是否存在
1
2
3
4
5
6
7
8
9
|
True
True
True
False
|
glob()
列舉文件
1
2
3
4
5
6
7
8
9
10
11
|
[PosixPath(
'pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
[PosixPath(
'docs/conf.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
|
9
'some text'
|
resolve()
Make the path absolute, resolving any symlinks. A new path object is returned
1
2
3
4
5
|
PosixPath(
'.')
PosixPath(
'/home/antoine/pathlib')
|
rmdir()
刪除目錄,目錄必須為空
touch(mode=0o777, exist_ok=True)
創建空文件