【Python Snippets】Pathlib 模塊

概要

面向對象的文件系統路徑操做模塊html

pathlib-inheritance.png

pure paths: 單純的路徑操做,不提供 I/O 操做
concrete paths: 路徑計算操做 + I/O 操做

經常使用的操做

1. 路徑的屬性

列出全部父目錄、父目錄、文件名或目錄名、文件前綴、文件後綴等...python

from pathlib import Path

p = Path('./test/filename.text')

p.parents                 # 全部父目錄 
>> WindowsPath.parents

p.parent                  # 父目錄
>> test

p.name                    # 文件名或目錄名
>> filename.text

p.stem                    # 文件前綴
>> filename

p.suffix                  # 文件後綴
>> .text

p.is_dir()                # 文件夾判斷
>> False        

p.is_file()               # 文件判斷
>> True

p.exists()                # 路徑是否存在
>> True

p.stat()                  # 獲取路徑屬性
>> os.stat_result(st_mode=16895, st_ino=7036874417855445, st_dev=2287178555, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1576075587, st_mtime=1576075562, st_ctime=1576075197)

2. 路徑的操做

建立文件夾、路徑鏈接、寫文件、讀文件、遍歷子路徑等...git

from pathlib import Path

# 建立文件夾
base_path = Path('dir/child_dir')
base_path.mkdir(exist_ok=True, parents=True)           

# 路徑鏈接
file_path = base_path / Path('file.text')                

# 建立文件
file_path.touch(exist_ok=True)                          

# 寫文件
with file_path.open(mode='w', encoding='utf-8') as f:     
    f.write('Hello World')

# 讀文件
with file_path.open(mode='r') as f:                       
    print(f.read())

# 遍歷子路徑
for path in p.iterdir():                                  
    print(path)

# 遞歸遍歷子路徑 (正則)
for item in base_path.rglob('*.text'):                   
    print(item)

# 移動文件夾
new_path = base_path / Path('new_file.text')
file_path.replace(new_path)
 
# 刪除文件 
new_path.unlink()

# 刪除文件夾(必須爲空)
new_path.parent.rmdir()

附錄

os 和 os.path pathlib 說明
os.path.abspath() Path.resolve() 獲取 path 的絕對路徑
os.path.chmod() Path.chmod() 改變 path 的權限
os.path.mkdir() Path.mkdir() 建立文件夾
os.path.rename() Path.rename() path 重命名
os.path.replace() Path.replace() path 重命名 (新路徑存在則替換)
os.path.remove(), os.unlink() Path.unlink() 刪除 path
os.path.cwd() Path.cwd() 當前工做路徑(current working directory)
os.path.exists() Path.exists() path 是否存在
os.path.expanduser() Path.expanduser() path 添加當前用戶
os.path.isdir() Path.is_dir() 是否爲文件夾
os.path.isfile() Path.is_file() 是否爲文件
os.path.islink() Path.is_symlink() 是否爲軟連接
os.stat() Path.stat(), Path.owner(), Path.group() path 的屬性
os.path.samefile() Path.samefile() 是否爲相同文件
os.path.isabs() PurePath.is_absolute() 是否爲絕對路徑
os.path.join() PurePath.joinpath() 路徑鏈接操做
os.path.dirname() PurePath.parent 前綴路徑
os.path.basename() PurePath.name 路徑名稱
os.path.splitext() PurePath.suffix 路徑後綴

參考

https://docs.python.org/zh-cn/3/library/pathlib.htmlgithub

https://xin053.github.io/2016/07/03/pathlib%E8%B7%AF%E5%BE%84%E5%BA%93%E4%BD%BF%E7%94%A8%E8%AF%A6%E8%A7%A3/ui

相關文章
相關標籤/搜索