pathlib & os.path
pathlib (Python 3.4+) provides an object-oriented API for file system paths. It is the modern alternative to the string-based os.path module.
Creating Path Objects
from pathlib import Path
p = Path("/home/user/documents/report.pdf")
cwd = Path.cwd()
home = Path.home()Path Properties
p = Path("/home/user/data/report.csv")
print(p.name) # report.csv
print(p.stem) # report
print(p.suffix) # .csv
print(p.parent) # /home/user/data
print(p.parts) # ('/', 'home', 'user', 'data', 'report.csv')Building Paths
base = Path("/projects")
full = base / "myapp" / "config" / "settings.json"
print(full)Checking & Operations
p = Path("data.txt")
print(p.exists())
print(p.is_file())
print(p.is_dir())
p.touch() # create file
p.write_text("hello", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
p.unlink() # delete fileGlobbing & Iterating
d = Path("/home/user")
for f in d.glob("*.txt"):
print(f)
for f in d.rglob("*.py"): # recursive
print(f)os.path Equivalents
import os
print(os.path.join("/home", "user", "file.txt"))
print(os.path.exists("/home/user"))
print(os.path.basename("/home/user/file.txt")) # file.txt
print(os.path.splitext("report.csv")) # ('report', '.csv')