python?文件管理庫?Path常用操作
1 Path庫能做什么:
Path庫是python常見的文件操作庫(以對象形式操作文件路徑),可以進行以下操作:
- 文件路徑的拼接(example:
test / Your_path / files) - 文件地址的提取(提取名稱、后綴、全程......)
- 層級關(guān)系訪問
- 查詢文件是否存在
- 創(chuàng)建目錄
- .............(基本上文件操作都夠用的實用庫)
2 Path 與 os 庫的優(yōu)勢 (可選)
(了解文件操作庫os的可以查看,不了解建議略過)
from pathlib import Path
import os
def get_base_name_vs_os(input_file_path:str):
'''
獲取當前py文件的完整名稱、不帶后綴名稱、后綴
:return:
'''
fpath_os = input_file_path
fpath_path = Path(input_file_path)
#u can debug this function and try to input-> type(fpath_path) in ur IDE-debug window,u can see <class 'pathlib.WindowsPath'>
print(
f'os method: {os.path.basename(fpath_os)}, {os.path.basename(os.path.splitext(fpath_os)[0])}, {os.path.splitext(fpath_os)[-1]}'
)
print(
f'Path method: {fpath_path.name}, {fpath_path.stem}, {fpath_path.suffix}'
)
return
if __name__ == '__main__':
get_base_name_vs_os(r'your_file_path_like_C:\window')優(yōu)勢:
Path庫相比os庫有更全的封裝接口,能夠快速且便攜地獲取想要的文件地址,同樣的實現(xiàn)步驟可能需要好幾層os- 操作對象為
Object(即面向?qū)ο螅?,可以很方便調(diào)用類方法,而os需要調(diào)用os庫,相對來說繁瑣一些
劣勢:
- 雖然在很多方面完勝
os,但本質(zhì)是 不可哈希 的類型——object,類 類型,在寫接口兼容、調(diào)用路徑時需要注意。 - 其他兼容性問題。
3 Path庫常用操作:
3.1 初始化路徑
想初始化Path對象路徑很簡單,和其他類對象一樣,只需要Path(your_path)即可獲得對應的路徑對象。
def init_path(): input_path = Path(r"your_input_path_test.py")#直接通過Path 初始化 print(input_path) return input_path
除了直接通過單一變量初始化路徑,還能通過以下示例進行初始化:
input_path = Path(r"C:\\","Windows","your_dir") #構(gòu)造 c盤,window/your_dir的文件路徑,可以傳入多個路徑,返回他們按順序構(gòu)造的路徑 input_path = input_path / "hello_world.py"
3.2 獲取文件地址(文件名稱【帶后綴、不帶后綴】及后綴)
假設(shè)已經(jīng)獲取了文件對象的變量為:input_path = Path("your_path")
- 文件名稱(完整帶后綴):用
input_path.name即可 ,返回帶后綴的文件名稱【依舊是Path對象】 - 文件名稱(不帶后綴):用
input_path.stem即可,stem有莖的意思,假設(shè)文件路徑像一朵花,地上的花就包含了花朵和根莖,少了花朵部分,根莖也可以被認為是不帶后綴(花朵)的了。 - 文件名稱(后綴):用
input_path.suffix即可 ,suffix翻譯過來就是后綴,返回文件后綴【str】- 但是這里要注意,如果有多個后綴,如
library.tar.gz, 則會返回最后一個后綴,如果想要獲取n個后綴,請使用suffixes。
- 但是這里要注意,如果有多個后綴,如
def get_path_name_stem_suffix(input_path:Path):
name = input_path.name
name_without_suffix = input_path.stem
suffix = input_path.suffix
print(f'\n u get it-> name:{name} ; stem: {name_without_suffix} ; suffix:{suffix}\n')
return官方示例:
name:
PurePosixPath('my/library/setup.py').name
PureWindowsPath('//some/share/setup.py').name
PureWindowsPath('//some/share').namestem:
PurePosixPath('my/library.tar.gz').stem
PurePosixPath('my/library.tar').stem
PurePosixPath('my/library').stemsuffix:
PurePosixPath('my/library/setup.py').suffix
PurePosixPath('my/library.tar.gz').suffix
PurePosixPath('my/library').suffix3.3 獲取路徑狀態(tài)
當我們對路徑進行操作時,需要判斷當前路徑所處的位置、是否為文件、是否為文件夾等。
假設(shè)已經(jīng)獲取了文件對象的變量為:input_path = Path("your_path")
是否存在:返回 bool: (True or False)
exist = input_path.exists()
是否是文件夾:返回 bool: (True or False)
whether_dir = input_path.is_dir()
是否是文件:返回 bool: (True or False)
whether_file = input_path.is_file()
常用狀態(tài)(總):
def get_path_status(input_path:Path):
exist = input_path.exists()
whether_dir = input_path.is_dir()
whether_file = input_path.is_file()
print(f'\n file exist status:{exist}, dir :{whether_dir}, file:{whether_file}\n')
return3.4 獲取當前/父文件夾
? 使用os庫時,對父文件夾的控制相對較為繁瑣,而Path對于文件夾層級的管理比較簡單。假設(shè)我們有一個路徑為:“C:\Windows\Learning\pycharm\hello_world.py”,那他的當前路徑為:pycharm,父路徑為:Learning ,可以使用以下操作獲取
def get_father_and_local_dir(input_path:Path):
local_dir = input_path.parent
all_father_dir = input_path.parents #返回的是 Path.parents,類似于可迭代對象,如果想要直接看所有結(jié)構(gòu),就list化
for father_dir,idx in enumerate(all_father_dir):
output = f'(father_{idx}){father_dir}'
print(output,end='') #迭代參考,可以自行debug體會一下
print('') #純美化用
all_father_dirs = list(input_path.parents) # list(Path.parents), u can easily get value
father_1_dir = str(input_path.parents[1]) # get idx=1[start in 0 index] parents and str the value
print(f'local_dir:{local_dir}, father_1_dir:{father_1_dir} ,all_father_dir:{all_father_dirs} \n')PS:
- 通常獲取當前目錄,使用
.parent就夠用了,他同樣返回當前父文件夾的Path對象 - 獲取前n個父級文件夾路徑就使用
.parents就好,但注意他返回的是可迭代對象,不能直接使用,需要直接使用就套list- 返回的可迭代對象從0開始,也就是說,
input_path.parents[0]==local_dir = input_path.parent
- 返回的可迭代對象從0開始,也就是說,
3.5 路徑拼接
在上文初始化時,我們提及了其中一種路徑拼接的方式(調(diào)用初始化函數(shù))
input_path = Path(r"C:\\","Windows","your_dir") #構(gòu)造 c盤,window/your_dir的文件路徑,可以傳入多個路徑,返回他們按順序構(gòu)造的路徑 input_path = input_path / "hello_world.py"
除此之外,還有函數(shù)方式進行拼接:
def join_path(input_path:Path,sub_paths=('hello','world')):
from copy import deepcopy
example_1,example_2 = deepcopy(input_path), deepcopy(input_path)
for sub_path in sub_paths:
example_1 = example_1 / sub_path #兩種路徑拼接方式等價,個人建議使用 重載的”/“,方便簡潔
example_2 = example_2.joinpath(sub_path)
print(f'{"*"*50}\n'+f'{example_1}; {example_2}; '+f'\n{"*"*50}\n')3.6 確保文件路徑存在(創(chuàng)建路徑)
def make_sure_dir_exist(input_path:Path): input_path.mkdir(parents=True,exist_ok=True) #相對固定,類似于模板,父文件夾自動創(chuàng)建True,文件夾存在不會重復創(chuàng)建 True
使用 mkdir這個接口即可,一般來說都會使用這樣的配置:
parents: 父文件夾是否需要創(chuàng)建exist_ok: 路徑已存在文件夾的情況(是否處理)
Create a new directory at this given path. If mode is given, it is combined with the process’
umaskvalue 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 -pcommand).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 -pcommand), 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.
3.7 計算文件路徑間的差異(進階)
接口介紹:
def cal_path_diff(path_1:Path, path_2:Path=Path.cwd()): ''' 計算兩個路徑間的相對路徑差 :param path_1: 子集路徑【范圍更廣】 :param path_2: 父集路徑【范圍更小】 這種方式僅適用于父集和子集之間,無依附關(guān)系則會報錯 ''' try: diff = path_1.relative_to(path_2) diff_2 = path_2.relative_to(path_1) print(str(diff), '\n') # print(str(diff_2),"\n") #如果path_2是path_1的父集,就會error【反之同理】,只能從子集計算父集的差距路徑 except Exception as e: raise e
官方參考:
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pathlib.py", line 694, in relative_to
.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute3.8 獲取當前目錄下 指定后綴文件(略進階)
def find_files(input_path:Path, files_suffix:str=".jpg"):
'''
找文件下的文件(通過通配符查找)
:param input_path: 輸入路徑
:param files_suffix: 匹配的后綴
可以自己換一下后綴,或者不要后綴,換一下路徑,debug體會一下,還能配合列表推導式,還算實用,但我覺得os.walk對文件遍歷好一些
'''
specimen_1 = input_path.glob(f'*{files_suffix}') #不遞歸進入
specimen_2 = input_path.glob(f'**/*{files_suffix}') #遞歸進入,same to : path.rglob("*.files_suffix")
print(f'specimen_1:{list(specimen_1)} \n specimen_2:{list(specimen_2)}\n')真要大面積遍歷文件的話,我建議用os.walk會好一些【參考 chapter2】
4.參考文檔
最常使用的基本上是上面這些了,還有什么需要的再查再找就好了,基礎(chǔ)解析到這里應該夠用了,bey~,感謝你看到這里,希望這篇文章能給你帶來一些幫助,喜歡的話幫我點個贊吧。
5.code
Main_test:
from pathlib import Path
def init_path():
# input_path = Path(r"E:\Learning\test.py")
input_path = Path(r"E:\\",r"Learning","os_vs_path.py")
print(input_path)
return input_path
def get_path_name_stem_suffix(input_path:Path):
name = input_path.name
name_without_suffix = input_path.stem
suffix = input_path.suffix
print(f'u get it-> name:{name} ; stem: {name_without_suffix} ; suffix:{suffix}\n')
return
def get_path_status(input_path:Path):
exist = input_path.exists()
whether_dir = input_path.is_dir()
whether_file = input_path.is_file()
print(f'file exist status:{exist}, dir :{whether_dir}, file:{whether_file}\n')
return
def get_father_and_local_dir(input_path:Path):
local_dir = input_path.parent
all_father_dir = input_path.parents #返回的是 Path.parents,類似于迭代器,如果想要直接看所有結(jié)構(gòu),就list化
for father_dir,idx in enumerate(all_father_dir):
output = f'(father_{idx}){father_dir}'
print(output,end='') #迭代參考,可以自行debug體會一下
print('') #純美化用
all_father_dirs = list(input_path.parents) # list(Path.parents), u can easily get value
father_1_dir = str(input_path.parents[1]) # get idx=1[start in 0 index] parents and str the value
print(f'local_dir:{local_dir}, father_1_dir:{father_1_dir} ,all_father_dir:{all_father_dirs} \n')
def join_path(input_path:Path,sub_paths=('hello','world')):
from copy import deepcopy
example_1,example_2 = deepcopy(input_path), deepcopy(input_path)
for sub_path in sub_paths:
example_1 = example_1 / sub_path #兩種路徑拼接方式等價,個人建議使用 重載的”/“,方便簡潔
example_2 = example_2.joinpath(sub_path)
print(f'{"*"*50}\n'+f'{example_1}; {example_2}; '+f'\n{"*"*50}\n')
def make_sure_dir_exist(input_path:Path):
input_path.mkdir(parents=True,exist_ok=True) #相對固定,類似于模板,父文件夾自動創(chuàng)建True,文件夾存在不會重復創(chuàng)建 True
def cal_path_diff(path_1:Path, path_2:Path=Path.cwd()):
'''
計算兩個路徑間的相對路徑差
:param path_1: 子集路徑【范圍更廣】
:param path_2: 父集路徑【范圍更小】
這種方式僅適用于父集和子集之間,無依附關(guān)系則會報錯
'''
try:
diff = path_1.relative_to(path_2)
diff_2 = path_2.relative_to(path_1)
print(str(diff), '\n')
# print(str(diff_2),"\n") #如果path_2是path_1的父集,就會error【反之同理】,只能從子集計算父集的差距路徑
except Exception as e:
raise e
def find_files(input_path:Path, files_suffix:str=".jpg"):
'''
找文件下的文件(通過通配符查找)
:param input_path: 輸入路徑
:param files_suffix: 匹配的后綴
可以自己換一下后綴,或者不要后綴,換一下路徑,debug體會一下
'''
specimen_1 = input_path.glob(f'*{files_suffix}') #不遞歸進入
specimen_2 = input_path.glob(f'**/*{files_suffix}') #遞歸進入,same to : path.rglob("*.files_suffix")
print(f'specimen_1:{list(specimen_1)} \n specimen_2:{list(specimen_2)}\n')
if __name__ == '__main__':
t_path = init_path()
get_path_name_stem_suffix(t_path)
get_path_status(input_path=t_path)
get_father_and_local_dir(t_path)
join_path(t_path)
find_files(t_path)
cal_path_diff(t_path,Path("C:\\Windows")) #記得刪掉后面路徑再試一次,就不會報錯了Os Vs Path:
from pathlib import Path
import os
def get_base_name_vs_os(input_file_path:str):
'''
獲取當前py文件的完整名稱、不帶后綴名稱、后綴
:return:
'''
fpath_os = input_file_path
fpath_path = Path(input_file_path)
#u can debug this function and try to input-> type(fpath_path) in ur IDE-debug window,u can see <class 'pathlib.WindowsPath'>
print(
f'os method: {os.path.basename(fpath_os)}, {os.path.basename(os.path.splitext(fpath_os)[0])}, {os.path.splitext(fpath_os)[-1]}'
)
print(
f'Path method: {fpath_path.name}, {fpath_path.stem}, {fpath_path.suffix}'
)
return
if __name__ == '__main__':
get_base_name_vs_os(r'E:\Learning\os_vs_path.py')到此這篇關(guān)于python 文件管理庫 Path 解析的文章就介紹到這了,更多相關(guān)python 文件管理庫 Path內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python庫pydantic數(shù)據(jù)驗證和設(shè)置管理庫的用途
- Python Loguru輕松靈活的日志管理庫基本用法探索
- Python中pathlib庫的使用小結(jié)
- Python使用lxml庫和Xpath提取網(wǎng)頁數(shù)據(jù)的完整指南與最佳實戰(zhàn)
- Python?HTML解析:BeautifulSoup,Lxml,XPath使用教程
- Python開發(fā)教程之os.path的常用操作總結(jié)
- Python使用sys.path查看當前的模塊搜索路徑
- python中sys.path.append的作用
- python+selenium使用xpath定位的問題及解決
相關(guān)文章
Python實現(xiàn)按照指定要求逆序輸出一個數(shù)字的方法
這篇文章主要介紹了Python實現(xiàn)按照指定要求逆序輸出一個數(shù)字的方法,涉及Python針對字符串的遍歷、判斷、輸出等相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
python 函數(shù)內(nèi)部修改外部變量的方法
今天小編就為大家分享一篇python 函數(shù)內(nèi)部修改外部變量的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python-opencv中的cv2.inRange函數(shù)用法說明
這篇文章主要介紹了python-opencv中的cv2.inRange函數(shù)用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
開源軟件包和環(huán)境管理系統(tǒng)Anaconda的安裝使用
Anaconda是一個用于科學計算的Python發(fā)行版,支持 Linux, Mac, Windows系統(tǒng),提供了包管理與環(huán)境管理的功能,可以很方便地解決多版本python并存、切換以及各種第三方包安裝問題。2017-09-09
Python OpenCV 使用滑動條來調(diào)整函數(shù)參數(shù)的方法
這篇文章主要介紹了Python OpenCV 使用滑動條來調(diào)整函數(shù)參數(shù)的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
Python中FastAPI項目使用 Annotated的參數(shù)設(shè)計的處理方案
FastAPI 是一個非?,F(xiàn)代化和高效的框架,非常適合用于構(gòu)建高性能的 API,FastAPI 是一個用于構(gòu)建 API 的現(xiàn)代、快速(高性能)web 框架,基于 Python 類型提示,這篇文章主要介紹了Python中FastAPI項目使用 Annotated的參數(shù)設(shè)計,需要的朋友可以參考下2024-08-08

