安裝

無需安裝,這是 Python 的內建函式庫

基本用法

建立 Path 物件

Path是 pathlib 模組中最重要的物件

from pathlib import Path

current_work_directory = Path.cwd()

# Windows 系統
# pathlib.Path(r'C:\Users\kirin\Desktop\file.txt')

readme_file = Path.home().joinpath("Code", "pythonlab", "Readme.md")
# readme_file = Path.home() / "Code" / "pythonlab" / "Readme.md"

Path 的常用屬性

from pathlib import Path

readme_file = Path.home().joinpath("Code", "pythonlab", "Readme.md")
# readme_file = Path.home() / "Code" / "pythonlab" / "Readme.md"

// Readme.md
print(readme_file.name)
// .md
print(readme_file.suffix)
// Readme
print(readme_file.stem)
// /home/kirin/Code/pythonlab
print(readme_file.parent)
// /
print(readme_file.anchor)

讀取檔案

from pathlib import Path

readme = pathlib.Path.cwd() / "Code" / "pythonlab" / "Readme.md"

readme.read_text()

參考資料

Python Ofiicial: pathlib — Object-oriented filesystem paths

Python 3's pathlib Module: Taming the File System

Last modified: 2023-02-25

Author

Comments

Write a Reply or Comment

Your email address will not be published.