python中pathlib模塊的基本用法與總結(jié)
前言
相比常用的 os.path而言,pathlib 對(duì)于目錄路徑的操作更簡(jiǎn)介也更貼近 Pythonic。但是它不單純是為了簡(jiǎn)化操作,還有更大的用途。
pathlib 是Python內(nèi)置庫(kù),Python 文檔給它的定義是:The pathlib module – object-oriented filesystem paths(面向?qū)ο蟮奈募到y(tǒng)路徑)。pathlib 提供表示文件系統(tǒng)路徑的類,其語(yǔ)義適用于不同的操作系統(tǒng)。
更多詳細(xì)的內(nèi)容可以參考官方文檔:https://docs.python.org/3/library/pathlib.html#methods
1. pathlib模塊下Path類的基本使用
from pathlib import Path path = r'D:\python\pycharm2020\program\pathlib模塊的基本使用.py' p = Path(path) print(p.name) # 獲取文件名 print(p.stem) # 獲取文件名除后綴的部分 print(p.suffix) # 獲取文件后綴 print(p.parent) # 相當(dāng)于dirname print(p.parent.parent.parent) print(p.parents) # 返回一個(gè)iterable 包含所有父目錄 for i in p.parents: print(i) print(p.parts) # 將路徑通過(guò)分隔符分割成一個(gè)元組
運(yùn)行結(jié)果如下:
pathlib模塊的基本使用.py
pathlib模塊的基本使用
.py
D:\python\pycharm2020\program
D:\python
<WindowsPath.parents>
D:\python\pycharm2020\program
D:\python\pycharm2020
D:\python
D:\
('D:\\', 'python', 'pycharm2020', 'program', 'pathlib模塊的基本使用.py')
- Path.cwd():Return a new path object representing the current directory
- Path.home():Return a new path object representing the user's home directory
- Path.expanduser():Return a new path with expanded ~ and ~user constructs
from pathlib import Path path_1 = Path.cwd() # 獲取當(dāng)前文件路徑 path_2 = Path.home() p1 = Path('~/pathlib模塊的基本使用.py') print(path_1) print(path_2) print(p1.expanduser())
運(yùn)行結(jié)果如下:
D:\python\pycharm2020\program
C:\Users\Administrator
C:\Users\Administrator\pathlib模塊的基本使用.py
Path.stat():Return a os.stat_result object containing information about this path
from pathlib import Path import datetime p = Path('pathlib模塊的基本使用.py') print(p.stat()) # 獲取文件詳細(xì)信息 print(p.stat().st_size) # 文件的字節(jié)大小 print(p.stat().st_ctime) # 文件創(chuàng)建時(shí)間 print(p.stat().st_mtime) # 上次修改文件的時(shí)間 creat_time = datetime.datetime.fromtimestamp(p.stat().st_ctime) st_mtime = datetime.datetime.fromtimestamp(p.stat().st_mtime) print(f'該文件創(chuàng)建時(shí)間:{creat_time}') print(f'上次修改該文件的時(shí)間:{st_mtime}')
運(yùn)行結(jié)果如下:
os.stat_result(st_mode=33206, st_ino=3659174698076635, st_dev=3730828260, st_nlink=1, st_uid=0, st_gid=0, st_size=543, st_atime=1597366826, st_mtime=1597366826, st_ctime=1597320585)
543
1597320585.7657475
1597366826.9711637
該文件創(chuàng)建時(shí)間:2020-08-13 20:09:45.765748
上次修改該文件的時(shí)間:2020-08-14 09:00:26.971164
從不同.stat().st_屬性 返回的時(shí)間戳表示自1970年1月1日以來(lái)的秒數(shù),可以用datetime.fromtimestamp將時(shí)間戳轉(zhuǎn)換為有用的時(shí)間格式。
Path.exists():Whether the path points to an existing file or directory
Path.resolve(strict=False):Make the path absolute,resolving any symlinks. A new path object is returned
from pathlib import Path p1 = Path('pathlib模塊的基本使用.py') # 文件 p2 = Path(r'D:\python\pycharm2020\program') # 文件夾 absolute_path = p1.resolve() print(absolute_path) print(Path('.').exists()) print(p1.exists(), p2.exists()) print(p1.is_file(), p2.is_file()) print(p1.is_dir(), p2.is_dir()) print(Path('/python').exists()) print(Path('non_existent_file').exists())
運(yùn)行結(jié)果如下:
D:\python\pycharm2020\program\pathlib模塊的基本使用.py
True
True True
True False
False True
True
False
Path.iterdir():When the path points to a directory,yield path objects of the directory contents
from pathlib import Path p = Path('/python') for child in p.iterdir(): print(child)
運(yùn)行結(jié)果如下:
\python\Anaconda
\python\EVCapture
\python\Evernote_6.21.3.2048.exe
\python\Notepad++
\python\pycharm-community-2020.1.3.exe
\python\pycharm2020
\python\pyecharts-assets-master
\python\pyecharts-gallery-master
\python\Sublime text 3
Path.glob(pattern):Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind),The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing.
Note:Using the “**” pattern in large directory trees may consume an inordinate amount of time
遞歸遍歷該目錄下所有文件,獲取所有符合pattern的文件,返回一個(gè)generator。
獲取該文件目錄下所有.py文件
from pathlib import Path path = r'D:\python\pycharm2020\program' p = Path(path) file_name = p.glob('**/*.py') print(type(file_name)) # <class 'generator'> for i in file_name: print(i)
獲取該文件目錄下所有.jpg圖片
from pathlib import Path path = r'D:\python\pycharm2020\program' p = Path(path) file_name = p.glob('**/*.jpg') print(type(file_name)) # <class 'generator'> for i in file_name: print(i)
獲取給定目錄下所有.txt文件、.jpg圖片和.py文件
from pathlib import Path def get_files(patterns, path): all_files = [] p = Path(path) for item in patterns: file_name = p.rglob(f'**/*{item}') all_files.extend(file_name) return all_files path = input('>>>請(qǐng)輸入文件路徑:') results = get_files(['.txt', '.jpg', '.py'], path) print(results) for file in results: print(file)
Path.mkdir(mode=0o777, parents=False, exist_ok=False)
- Create a new directory at this given path. If mode is given, it is combined with the process' umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.
- If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
- If parents is false (the default), a missing parent raises FileNotFoundError.
- If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.
- If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.
Changed in version 3.5: The exist_ok parameter was added.
Path.rmdir():Remove this directory. The directory must be empty.
from pathlib import Path p = Path(r'D:\python\pycharm2020\program\test') p.mkdir() p.rmdir()
from pathlib import Path p = Path(r'D:\python\test1\test2\test3') p.mkdir(parents=True) # If parents is true, any missing parents of this path are created as needed p.rmdir() # 刪除的是test3文件夾
from pathlib import Path p = Path(r'D:\python\test1\test2\test3') p.mkdir(exist_ok=True)
- Path.unlink(missing_ok=False):Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead. If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist. If missing_ok is true, FileNotFoundError exceptions will be ignored. Changed in version 3.8:The missing_ok parameter was added.
- Path.rename(target):Rename this file or directory to the given target, and return a new Path instance pointing to target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.
- Path.open(mode=‘r', buffering=-1, encoding=None, errors=None, newline=None):Open the file pointed to by the path, like the built-in open() function does.
from pathlib import Path p = Path('foo.txt') p.open(mode='w').write('some text') target = Path('new_foo.txt') p.rename(target) content = target.open(mode='r').read() print(content) target.unlink()
2. 與os模塊用法的對(duì)比
總結(jié)
到此這篇關(guān)于python中pathlib模塊的基本用法與總結(jié)的文章就介紹到這了,更多相關(guān)python pathlib模塊用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)代碼統(tǒng)計(jì)工具
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)代碼統(tǒng)計(jì)工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09Python中DJANGO簡(jiǎn)單測(cè)試實(shí)例
這篇文章主要介紹了Python中DJANGO簡(jiǎn)單測(cè)試,實(shí)例分析了DJANGO的用法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-05-05python 發(fā)送郵件的示例代碼(Python2/3都可以直接使用)
這篇文章主要介紹了python 發(fā)送郵件的示例代碼,并且Python2/3都可以直接使用,感興趣的朋友可以參考下2020-12-12django inspectdb 操作已有數(shù)據(jù)庫(kù)數(shù)據(jù)的使用步驟
這篇文章主要介紹了django inspectdb 操作已有數(shù)據(jù)庫(kù)數(shù)據(jù)的使用步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02解決Jupyter NoteBook輸出的圖表太小看不清問(wèn)題
這篇文章主要介紹了解決Jupyter NoteBook輸出的圖表太小看不清問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04python中的format格式化、填充與對(duì)齊、數(shù)字格式化方式
format函數(shù)是Python中強(qiáng)大的字符串格式化方法,它允許程序員通過(guò)大括號(hào){}來(lái)為字符串中的插入點(diǎn)占位,并通過(guò)傳入?yún)?shù)進(jìn)行替換,{0}、{1}分別代表不同的參數(shù)2024-09-09淺談Python中的可變對(duì)象和不可變對(duì)象
下面小編就為大家?guī)?lái)一篇淺談Python中的可變對(duì)象和不可變對(duì)象。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07Python matplotlib實(shí)現(xiàn)圖表主題變換示例詳解
在畫(huà)圖的時(shí)候如果出現(xiàn)與圖表的顏色沖突或者看不清坐標(biāo)軸的情況,這時(shí)候可以通過(guò)更換坐標(biāo)軸風(fēng)格來(lái)解決,本文將為大家詳細(xì)介紹如何利用matplotlib實(shí)現(xiàn)圖表的主題樣式變換,需要的可以參考一下2022-03-03python編寫(xiě)腳本之pyautogui的安裝和使用教程
pyautogui一個(gè)神奇的圖像自動(dòng)化庫(kù),學(xué)會(huì)之后無(wú)所不能,下面這篇文章主要給大家介紹了關(guān)于python編寫(xiě)腳本之pyautogui的安裝和使用的相關(guān)資料,需要的朋友可以參考下2021-12-12Python多線程多進(jìn)程實(shí)例對(duì)比解析
這篇文章主要介紹了Python多線程多進(jìn)程實(shí)例對(duì)比解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03