首頁 > 軟體

Python中的pathlib庫使用詳解

2022-05-21 16:00:14

1. pathlib庫介紹

相比常用的 os.path 而言,pathlib 對於目錄路徑的操作更簡潔也更貼近 Pythonic(Python程式碼風格的)。但是它不單純是為了簡化操作,還有更大的用途

pathlib 是Python內建庫,Python 檔案給它的定義是:

The pathlib module – object-oriented filesystem paths(物件導向的檔案系統路徑)

pathlib 提供表示檔案系統路徑的類,其語意適用於不同的作業系統

2. pathlib庫下Path類的基本使用

2.1 獲取檔名

from pathlib import Path  # 匯入pathlib的Path類
import os
path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb"
p = Path(path)
print(f"獲取檔名:{p.name}")  # 獲取檔名:pathlib庫的使用.ipynb

2.2 獲取檔案字首和字尾

—— .stem & .suffix

from pathlib import Path
import os
path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb"
p = Path(path)
print(f"獲取字首:{p.stem}")  # 獲取字首:pathlib庫的使用
print(f"獲取字尾:{p.suffix}")  # 獲取字尾:.ipynb

2.3 獲取檔案的資料夾及上一級、上上級資料夾

—— .parent

from pathlib import Path
import os
path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb"
p = Path(path)
print(f"獲取當前檔案所屬資料夾:{p.parent}")
print(f"獲取上一級資料夾:{p.parent.parent}")
print(f"獲取上上一級資料夾:{p.parent.parent.parent}")
"""
獲取當前檔案所屬資料夾:/home/leovin/JupyterNotebookFolders
獲取上一級資料夾:/home/leovin
獲取上上一級資料夾:/home
"""

Note: 最上級的資料夾是一個/

2.4 獲取該檔案所屬的資料夾及其父資料夾

—— .parents

from pathlib import Path
import os
path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb"
p = Path(path)
print(f"獲取當前檔案所屬資料夾及其父資料夾:{p.parents}n")
# 遍歷
for idx, folder_path in enumerate(p.parents):
    print(f"No.{idx}: {folder_path}")
"""
獲取當前檔案所屬資料夾及其父資料夾:<PosixPath.parents>

No.0: /home/leovin/JupyterNotebookFolders
No.1: /home/leovin
No.2: /home
No.3: /
"""

2.5 檔案絕對路徑

按照/進行分割 —— .parts

from pathlib import Path
import os
path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb"
p = Path(path)
print(f"將檔案的絕對路徑按照`/`進行分割,返回一個tuple:{p.parts}n")
# 遍歷
for idx, element in enumerate(p.parts):
    print(f"No.{idx}: {element}")
"""
獲取當前檔案所屬資料夾及其父資料夾:<PosixPath.parents>
No.0: /
No.1: home
No.2: leovin
No.3: JupyterNotebookFolders
No.4: pathlib庫的使用.ipynb
"""

2.6 獲取當前工作目錄

—— Path.cwd()

from pathlib import Path
import os
path_1 = Path.cwd()
path_2 = os.getcwd()
print(f"Path.cwd(): {path_1}")
print(f"os.getcwd(): {path_2}")
"""
Path.cwd(): /home/leovin/JupyterNotebookFolders
os.getcwd(): /home/leovin/JupyterNotebookFolders
"""

2.7 獲取使用者

home目錄路徑 —— Path.home()系列

from pathlib import Path
print(f"獲取使用者home路徑: {Path.home()}")
"""
獲取使用者home路徑: /home/leovin
"""

2.8 獲取檔案詳細資訊

—— object.stat()

from pathlib import Path
p = Path("/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb")
print(f"獲取檔案詳細資訊: {p.stat()}n")
print(f"獲取檔案位元組大小: {p.stat().st_size}n")
print(f"獲取檔案建立時間: {p.stat().st_ctime}n")  # c: create
print(f"獲取檔案上次修改時間: {p.stat().st_mtime}n")  # m:: modify
"""
獲取檔案詳細資訊: os.stat_result(st_mode=33204, st_ino=23860358, st_dev=2052, st_nlink=1, st_uid=1000, st_gid=1000, st_size=12125, st_atime=1653039478, st_mtime=1653039478, st_ctime=1653039478)

獲取檔案位元組大小: 12125

獲取檔案建立時間: 1653039478.703161

獲取檔案上次修改時間: 1653039478.703161
"""

可以看到,object.stat().xxx就是在呼叫attr 

2.9 檢查目錄或者檔案是否存在

—— Path("路徑").exists()

from pathlib import Path
print(f"目標路徑的檔案是否存在: {Path('/home/leovin/JupyterNotebookFolders/xxx').exists()}")  # False
print(f"目標路徑的檔案是否存在: {Path('/home/leovin/JupyterNotebookFolders').exists()}")  # True

2.10 檢查指定指定路徑是否為folder或者file

—— Path("路徑").is_file() & Path("路徑").is_dir()

from pathlib import Path
print(f"目標路徑是否為檔案: {Path('/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb').is_file()}")  # True
print(f"目標路徑是否為資料夾: {Path('/home/leovin/JupyterNotebookFolders/').is_dir()}")  # True

directory為資料夾

2.11 將相對路徑轉換為絕對路徑

—— Path("路徑").resolve()

from pathlib import Path
print(f"目標路徑是否為檔案: {Path('/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb').is_file()}")  # True
print(f"目標路徑是否為資料夾: {Path('/home/leovin/JupyterNotebookFolders/').is_dir()}")  # True

2.12 遍歷一個目錄

—— Path("路徑").iterdir()

from pathlib import Path
path_object = Path("/home/leovin/JupyterNotebookFolders/").iterdir()
print(f"path_object: {path_object}")  # path_object: <generator object Path.iterdir at 0x7f0ca0061c10>
# 迭代目錄物件
for idx, element in enumerate(path_object):
    print(f"No.{idx}: {element}")
"""
path_object: <generator object Path.iterdir at 0x7f0ca0061c10>
No.0: /home/leovin/JupyterNotebookFolders/temp
No.1: /home/leovin/JupyterNotebookFolders/torch.meshgrid().ipynb
No.2: /home/leovin/JupyterNotebookFolders/array.argsort().ipynb
No.3: /home/leovin/JupyterNotebookFolders/切片....ipynb
No.4: /home/leovin/JupyterNotebookFolders/logging資訊.log
No.5: /home/leovin/JupyterNotebookFolders/Python中類的私有變數、私有方法、靜態方法.ipynb
No.6: /home/leovin/JupyterNotebookFolders/temp_file.ipynb
No.7: /home/leovin/JupyterNotebookFolders/example.log
No.8: /home/leovin/JupyterNotebookFolders/Python語法.ipynb
No.9: /home/leovin/JupyterNotebookFolders/.ipynb_checkpoints
No.10: /home/leovin/JupyterNotebookFolders/craw.data.txt
No.11: /home/leovin/JupyterNotebookFolders/test.txt
No.12: /home/leovin/JupyterNotebookFolders/logging的學習.ipynb
No.13: /home/leovin/JupyterNotebookFolders/Test.ipynb
No.14: /home/leovin/JupyterNotebookFolders/演演算法題
No.15: /home/leovin/JupyterNotebookFolders/functions.ipynb
No.16: /home/leovin/JupyterNotebookFolders/mask轉0&1.ipynb
No.17: /home/leovin/JupyterNotebookFolders/Multi_Task_in_Python.ipynb
No.18: /home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb
No.19: /home/leovin/JupyterNotebookFolders/三種啟用函數繪製.ipynb
"""

2.13 獲取所有符合pattern的檔案

—— Path("路徑").glob("folder1/xxx.格式")

from pathlib import Path
pattern = "JupyterNotebookFolders/*.ipynb"
glob_generator = Path("/home/leovin/").glob(pattern)
# 遍歷返回的物件 -> 返回的是絕對路徑
for idx, element in enumerate(glob_generator):
    print(f"No.{idx}: {element}")
"""
No.0: /home/leovin/JupyterNotebookFolders/torch.meshgrid().ipynb
No.1: /home/leovin/JupyterNotebookFolders/array.argsort().ipynb
No.2: /home/leovin/JupyterNotebookFolders/切片....ipynb
No.3: /home/leovin/JupyterNotebookFolders/Python中類的私有變數、私有方法、靜態方法.ipynb
No.4: /home/leovin/JupyterNotebookFolders/temp_file.ipynb
No.5: /home/leovin/JupyterNotebookFolders/Python語法.ipynb
No.6: /home/leovin/JupyterNotebookFolders/logging的學習.ipynb
No.7: /home/leovin/JupyterNotebookFolders/Test.ipynb
No.8: /home/leovin/JupyterNotebookFolders/functions.ipynb
No.9: /home/leovin/JupyterNotebookFolders/mask轉0&1.ipynb
No.10: /home/leovin/JupyterNotebookFolders/Multi_Task_in_Python.ipynb
No.11: /home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb
No.12: /home/leovin/JupyterNotebookFolders/三種啟用函數繪製.ipynb
"""

2.14 刪除檔案(非目錄)

—— Path("路徑").unlink()

from pathlib import Path
# 當前資料夾下的txt檔案
for idx, element in enumerate(Path("./").glob("*.txt")):
    print(f"No.{idx}: {element}")
print("-" * 30)
"""
    刪除指定的檔案(非目錄)
        1. 是真的刪除而非unlink
        2. 如果檔案不存在則儲存
"""
try:
    Path("./will_be_deleted.txt").unlink()
except Exception as e:
    print(f"刪除檔案發生錯誤,原因為: {e}")
# 當前資料夾下的txt檔案
for idx, element in enumerate(Path("./").glob("*.txt")):
    print(f"No.{idx}: {element}")
"""
No.0: will_be_deleted.txt
No.1: craw.data.txt
No.2: test.txt
------------------------------
No.0: craw.data.txt
No.1: test.txt

報錯的輸出:
No.0: craw.data.txt
No.1: test.txt
------------------------------
刪除檔案發生錯誤,原因為: [Errno 2] No such file or directory: 'will_be_deleted.txt'
No.0: craw.data.txt
No.1: test.txt
"""

3. pathlib庫與os庫的對比

ospathlib描述英文說明
os.path.abspath(("檔案路徑"))Path("檔案路徑").resolve()將路徑轉換為絕對路徑-
os.chmod()Path("檔案路徑").chmod(xxx)更改檔案許可權change mode
os.mkdir(("檔案路徑"))Path("檔案路徑").mkdir()新建資料夾make directory
os.rename("檔案路徑", "xxx")Path("檔案路徑").rename("xxx")重新命名檔案/資料夾名稱-
os.replace(a, b)Path("檔案路徑").replace(a, b)替換字串-
os.rmdir()Path("檔案路徑").rmdir()刪除資料夾(裡面必須是空的)remove directory
os.remove("檔案路徑") / os.unlink("檔案路徑")Path("檔案路徑").unlink()刪除檔案(非目錄)-
os.getcwd()Path("檔案路徑").cwd()獲取當前檔案工作目錄current work directory
os.path.isdir()Path("檔案路徑").is_dir()判斷當前路徑是否為目錄-
os.path.isfile()Path("檔案路徑").is_file()判斷當前路徑是否為檔案-
os.stat()Path("檔案路徑").stat()返回當前路徑的資訊status
os.path.isabs()Path("檔案路徑").is_absolute()判斷當前路徑是否為絕對路徑-
os.path.basename()Path("檔案路徑").name返回檔案/目錄的基礎名稱(不帶路徑)-
os.path.dirname()Path("檔案路徑").parent返回路徑所屬資料夾名稱-
os.path.samefile()Path("檔案路徑").samefile(xxx)判斷兩個檔案是否相同-
os.path.splitext("檔案路徑")(Path("檔案路徑").stem, Path("檔案路徑").suffix)將檔名分離,分成字首和字尾stem + suffix

參考

https://www.jb51.net/article/193402.htm

https://docs.python.org/zh-cn/3/library/pathlib.html?highlight=pathlib

到此這篇關於Python中的pathlib庫的文章就介紹到這了,更多相關Python pathlib庫內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com