Python中的pathlib庫使用詳解

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庫的對比

os pathlib 描述 英文說明
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#module-pathlib

到此這篇關於Python中的pathlib庫的文章就介紹到這瞭,更多相關Python pathlib庫內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: