Python中的面向物件檔案系統路徑 (pathlib)
pathlib模組提供了一種面向物件的方法來處理檔案系統路徑。該模組還提供了適用於各種作業系統的功能。此模組中定義的類分為兩種型別——純路徑型別和具體路徑型別。純路徑只能執行純計算操作,而具體路徑也能夠執行I/O操作。
pathlib模組定義了以下類:
| 序號 | 模組及描述 |
|---|---|
| 1 | PurePath 所有其他類的基類 |
| 2 | Path 繼承自PurePath。這是一個具體類,表示檔案系統路徑。 |
| 3 | PosixPath 非Windows作業系統的Path子類 |
| 4 | WindowsPath Windows系統的Path子類 |
| 5 | PurePosixPath 非Windows系統的PurePath子類 |
| 6 | PureWindowsPath Windows系統的PurePath子類 |
建立Path類例項時,它將根據您的系統自動返回WindowsPath或PosixPath。
請注意,也可以直接建立WindowsPath或PosixPath物件,但只能在相同型別的系統上建立。
要建立Path物件,請使用以下語法:
>>> from pathlib import *
>>> p = Path(".")
>>> type(p)
<class 'pathlib.WindowsPath'>您可以看到,由於以上語句是在Windows系統上執行的,因此建立了WindowsPath物件。“.” 指的是當前目錄。
Path類在其內部定義了以下方法:
**absolute()** − 返回Path物件的絕對版本。
>>> p.absolute()
WindowsPath('C:/python36')**exists()** − 如果給定路徑存在,則返回true
>>> p = Path("mydir")
>>> p.exists()
False
>>> p = Path("etc")
>>> p.exists()
True**is_dir()** − 如果路徑是目錄,則返回true
>>> p = Path("etc")
>>> p.is_dir()
True
>>> p = Path("test.py")
>>> p.is_dir()
False**is_file()** − 如果路徑對應於檔案,則返回true
>>> p = Path("tmp.py")
>>> p.is_file()
True
>>> p = Path("etc")
>>> p.is_file()
False**iterdir()** − 返回一個生成器,生成與路徑對應的目錄中的檔名。
>>> p = Path("libs")
>>> for f in p.iterdir():
print (f)
libs\libpython36.a
libs\python3.lib
libs\python36.lib
libs\_tkinter.lib**mkdir()** − 如果不存在,則建立表示路徑的新目錄。
>>> p = Path("mydir")
>>> p.mkdir()
>>> p.absolute()
WindowsPath('C:/python36/mydir')
>>> p = Path("codes")
>>> p.mkdir()
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'codes'**open()** − 開啟Path物件表示的檔案並返回檔案物件。這類似於內建的open()函式。
>>> p = Path("Hello.py")
>>> f = p.open()
>>> f.readline()
'Hello Python'**read_bytes()** − 以二進位制模式開啟檔案,以二進位制形式讀取其資料並關閉。
>>> p = Path("Hello.py")
>>> f.read_bytes()
>>> p.read_bytes()
b'Hello Python'**read_text()** − 以文字模式開啟檔案以讀取文字,然後關閉。
>>> p = Path("Hello.py")
>>> p.read_text()
'Hello Python'**write_text()** − 開啟檔案,寫入文字並關閉。
>>> p = Path("Hello.py")
>>> p.write_text("Hello how are you?")
18**write_bytes()** − 將二進位制資料寫入檔案並關閉。
>>> p = Path("Hello.py")
>>> p.write_bytes(b'I am fine')
9**stat()** − 返回有關此路徑的資訊。
>>> p.stat() os.stat_result(st_mode = 16895, st_ino = 9570149208167477, st_dev = 1526259762, st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 0, st_atime = 1543085915, st_mtime = 1543085915, st_ctime = 1543085915)
**rmdir()** − 刪除與Path物件對應的目錄。
>>> p = Path("mydir")
>>> p.rmdir()**Path.cwd()** − 這是Path類的類方法。返回當前工作目錄的路徑
>>> Path.cwd()
WindowsPath('C:/python36')**Path.home()** − 這是Path類的類方法。返回主目錄的路徑
>>> Path.home()
WindowsPath('C:/Users/acer')“/”運算子用於構建路徑。
>>> p = Path(".")
>>> p1 = p/'codes'
>>> p1.absolute()
WindowsPath('C:/python36/codes')在這篇文章中,我們學習了pathlib模組中定義的面向物件檔案系統物件的API。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP