一文帶你掌握Python中pathlib模塊的用法
pathlib 模塊提供了表示文件系統(tǒng)路徑的類,可適用于不同的操作系統(tǒng)。使用 pathlib 模塊,相比于 os 模塊可以寫出更簡潔,易讀的代碼。pathlib 模塊中的 Path 類繼承自 PurePath,對 PurePath 中的部分方法進行了重載,相比于 os.path 有更高的抽象級別。本文將帶你學習如何使用 pathlib 模塊中的 Path 類讀寫文件、操縱文件路徑和基礎文件系統(tǒng),統(tǒng)計目錄下的文件類型以及查找匹配目錄下某一類型文件等。下面就開始進入我們的學習時刻。
1 獲取目錄
- Path.cwd(),返回文件當前所在目錄。
- Path.home(),返回用戶的主目錄。
應用示例:
from pathlib import Path currentPath = Path.cwd() homePath = Path.home() print("文件當前所在目錄:%s\n用戶主目錄:%s" %(currentPath, homePath))
2 目錄拼接
斜杠 / 操作符用于拼接路徑,比如創(chuàng)建子路徑。
應用示例:
from pathlib import Path currentPath = Path.cwd() newPath = currentPath / 'python-100' print("新目錄為:%s" %(newPath))
3 創(chuàng)建、刪除目錄
- Path.mkdir(),創(chuàng)建給定路徑的目錄。
- Path.rmdir(),刪除該目錄,目錄文件夾必須為空。
應用示例:
from pathlib import Path currentPath = Path.cwd() makePath = currentPath / 'python-100' makePath.mkdir() print("創(chuàng)建的目錄為:%s" %(nmakePath))
from pathlib import Path currentPath = Path.cwd() delPath = currentPath / 'python-100' delPath.rmdir() print("刪除的目錄為:%s" %(delPath))
4 讀寫文件
- Path.open(mode=’r’),以 “r” 格式打開 Path 路徑下的文件,若文件不存在即創(chuàng)建后打開。
- Path.read_bytes(),打開 Path 路徑下的文件,以字節(jié)流格式讀取文件內(nèi)容,等同 open 操作文件的 “rb” 格式。
- Path.read_text(),打開 Path 路徑下的文件,以 str 格式讀取文件內(nèi)容,等同 open 操作文件的 “r” 格式。
- Path.write_bytes(),對 Path 路徑下的文件進行寫操作,等同 open 操作文件的 “wb” 格式。
- Path.write_text(),對 Path 路徑下的文件進行寫操作,等同 open 操作文件的 “w” 格式。
應用示例:
from pathlib import Path currentPath = Path.cwd() mkPath = currentPath / 'python-100.txt' with mkPath.open('w') as f: # 創(chuàng)建并以 "w" 格式打開 python-100.txt 文件。 f.write('python-100') # 寫入 python-100 字符串。 f = open(mkPath, 'r') print("讀取的文件內(nèi)容為:%s" % f.read()) f.close()
from pathlib import Path currentPath = Path.cwd() mkPathText = currentPath / 'python-100-text.txt' mkPathText.write_text('python-100') print("讀取的文件內(nèi)容為:%s" % mkPathText.read_text()) str2byte = bytes('python-100', encoding = 'utf-8') mkPathByte = currentPath / 'python-100-byte.txt' mkPathByte.write_bytes(str2byte) print("讀取的文件內(nèi)容為:%s" % mkPathByte.read_bytes())
5 獲取文件所在目錄的不同部分字段
- Path.resolve(),通過傳入文件名,返回文件的完整路徑。
- Path.name,可以獲取文件的名字,包含后綴名。
- Path.parent,返回文件所在文件夾的名字。
- Path.stem,獲取文件名不包含后綴名。
- Path.suffix,獲取文件的后綴名。
- Path.anchor,獲取文件所在的盤符。
from pathlib import Path txtPath = Path('python-100.txt') nowPath = txtPath.resolve() print("文件的完整路徑為:%s" % nowPath) print("文件完整名稱為(文件名+后綴名):%s" % nowPath.name) print("文件名為:%s" % nowPath.stem) print("文件后綴名為:%s" % nowPath.suffix) print("文件所在的文件夾名為:%s" % nowPath.parent) print("文件所在的盤符為:%s" % nowPath.anchor)
6 文件、路徑是否存在判斷
- Path.exists(),判斷 Path 路徑是否指向一個已存在的文件或目錄,返回 True 或 False。
- Path.is_dir(),判斷 Path 是否是一個路徑,返回 True 或 False。
- Path.is_file(),判斷 Path 是否指向一個文件,返回 True 或 False。
from pathlib import Path currentPath = Path.cwd() / 'python' print(currentPath.exists()) # 判斷是否存在 python 文件夾,此時返回 False。 print(currentPath.is_dir()) # 判斷是否存在 python 文件夾,此時返回 False。 currentPath.mkdir() # 創(chuàng)建 python 文件夾。 print(currentPath.exists()) # 判斷是否存在 python 文件夾,此時返回 True。 print(currentPath.is_dir()) # 判斷是否存在 python 文件夾,此時返回 True。 currentPath = Path.cwd() / 'python-100.txt' print(currentPath.exists()) # 判斷是否存在 python-100.txt 文件,此時文件未創(chuàng)建返回 False。 print(currentPath.is_file()) # 判斷是否存在 python-100.txt 文件,此時文件未創(chuàng)建返回 False。 f = open(currentPath,'w') # 創(chuàng)建 python-100.txt 文件。 f.close() print(currentPath.exists()) # 判斷是否存在 python-100.txt 文件,此時返回 True。 print(currentPath.is_file()) # 判斷是否存在 python-100.txt 文件,此時返回 True。
7 文件統(tǒng)計以及匹配查找
- Path.iterdir(),返回 Path 目錄文件夾下的所有文件,返回的是一個生成器類型。
- Path.glob(pattern),返回 Path 目錄文件夾下所有與 pattern 匹配的文件,返回的是一個生成器類型。
- Path.rglob(pattern),返回 Path 路徑下所有子文件夾中與 pattern 匹配的文件,返回的是一個生成器類型。
# 使用 Path.iterdir() 獲取當前文件下的所有文件,并根據(jù)后綴名統(tǒng)計其個數(shù)。 import pathlib from collections import Counter currentPath = pathlib.Path.cwd() gen = (i.suffix for i in currentPath.iterdir()) print(Counter(gen))
import pathlib from collections import Counter currentPath = pathlib.Path.cwd() gen = (i.suffix for i in currentPath.glob('*.txt')) # 獲取當前文件下的所有 txt 文件,并統(tǒng)計其個數(shù)。 print(Counter(gen)) gen = (i.suffix for i in currentPath.rglob('*.txt')) # 獲取目錄中子文件夾下的所有 txt 文件,并統(tǒng)計其個數(shù)。 print(Counter(gen))
8 總結
本文給大家介紹了 Python 的 pathlib 模塊,為 Python 工程師對該模塊的使用提供了支撐,讓大家了解如何使用 pathlib 模塊讀寫文件、操縱文件路徑和基礎文件系統(tǒng),統(tǒng)計目錄下的文件類型以及查找匹配目錄下某一類型文件等。
到此這篇關于一文帶你掌握Python中pathlib模塊的用法的文章就介紹到這了,更多相關Python pathlib模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Pycharm報錯Non-zero?exit?code?(2)的完美解決方案
最近在使用pycharm安裝或升級模塊時出現(xiàn)了錯誤,下面這篇文章主要給大家介紹了關于Pycharm報錯Non-zero?exit?code?(2)的完美解決方案,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-06-06python設計微型小說網(wǎng)站(基于Django+Bootstrap框架)
這篇文章主要介紹了python設計微型小說網(wǎng)站(基于Django+Bootstrap框架),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-07-07PyCharm提示No Python Interpreter的正確解決辦法
剛學Python時,拿到一個Python項目,想用pycharm打開運行卻報錯了,這篇文章主要給大家介紹了關于PyCharm提示No Python Interpreter的正確解決辦法,需要的朋友可以參考下2023-10-10pycharm遠程連接vagrant虛擬機中mariadb數(shù)據(jù)庫
這篇文章主要介紹了pycharm遠程連接vagrant虛擬機中mariadb數(shù)據(jù)庫,需要的朋友可以參考下2020-06-06