日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python文件與路徑操作神器?pathlib_python

作者:微小冷 ? 更新時間: 2022-06-02 編程語言

pathlib中封裝了PurePath和Path類,前者用于處理路徑風格的字符串;后者是前者的子類,可直接處理路徑。

PurePath最甜的功能是重載了運算符,從而可以實現類似下面這種

>>> from pathlib import Path, PurePath
>>> pp = PurePath("E:/")
>>> pp
PureWindowsPath('E:/')
>>> pp/"test"
PureWindowsPath('E:/test')

對于PurePath對象來說,可調用下面的成員或成員函數:

其中,主文件名即去除后綴之后的文件名。

PurePath類中還有一些稍微復雜的函數,

>>> pp = PurePath("E:\Code\test.py")
# 用于匹配文件后綴
>>> pp.match("*.py")
True
# 去除基準路徑
>>> pp.relative_to("E:\\")
PureWindowsPath('Code\test.py')
# 更改文件名
>>> pp.with_name('test1.py')
PureWindowsPath('E:/test1.py')
# 更改后綴名
>>> pp.with_suffix(".md")
PureWindowsPath('E:/Code\test.md')
# 更改主文件名
>>> pp.with_stem("help.md")
PureWindowsPath('E:/help.md.py')

Path

Path是PurePath的子類,在PurePath的基礎上添加了一些判定函數,

? ?
判定函數 ,is_file,is_fifo,
is_block_device,is_char_device,
is_mount,is_symlink,is_socket

Path對象還可以打開并寫入數據,但令人絕望的是并沒有close函數,所以并不建議使用?;蛘哒f,這個Path.open不像是給程序員使用的,因為Path中提供了更加便捷的讀寫方式read_bytes,read_text以及write_bytes、write_text。

例如:

>>> p = Path(r'E:\Documents\00\0324\Test.txt')
>>> p.write_text("hello world")
11
>>> p.read_text()
'hello world'
>>>

此外,可用于直接操作文件和文件夾,提供了非常強大的文件處理功能。Path和os中提供的函數在功能上對應如下

原文鏈接:https://blog.csdn.net/m0_37816922/article/details/123715364

欄目分類
最近更新