您好,登錄后才能下訂單哦!
這篇文章主要介紹“Python中的pathlib庫如何使用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Python中的pathlib庫如何使用”文章能幫助大家解決問題。
相比常用的 os.path
而言,pathlib
對于目錄路徑的操作更簡潔也更貼近 Pythonic(Python代碼風格的)。但是它不單純是為了簡化操作,還有更大的用途。
pathlib
是Python內置庫,Python 文檔給它的定義是:
The pathlib module – object-oriented filesystem paths(面向對象的文件系統路徑)
pathlib
提供表示文件系統路徑的類,其語義適用于不同的操作系統。
from pathlib import Path # 導入pathlib的Path類 import os path = "/home/leovin/JupyterNotebookFolders/pathlib庫的使用.ipynb" p = Path(path) print(f"獲取文件名:{p.name}") # 獲取文件名:pathlib庫的使用.ipynb
—— .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
—— .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: 最上級的文件夾是一個/
—— .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: / """
按照/
進行分割 —— .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 """
—— 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 """
home
目錄路徑 —— Path.home()
系列
from pathlib import Path print(f"獲取用戶home路徑: {Path.home()}") """ 獲取用戶home路徑: /home/leovin """
—— 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
—— Path("路徑").exists()
from pathlib import Path print(f"目標路徑的文件是否存在: {Path('/home/leovin/JupyterNotebookFolders/xxx').exists()}") # False print(f"目標路徑的文件是否存在: {Path('/home/leovin/JupyterNotebookFolders').exists()}") # True
—— 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為文件夾
—— 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
—— 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 """
—— 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 """
—— 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 """
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 |
關于“Python中的pathlib庫如何使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。