Python’s pathlib
module makes file system paths easier to work with.
It gives you an object-oriented approach instead of dealing with os
and os.path
.
✅ Cleaner syntax (OOP style)
✅ Cross-platform (Windows, Linux, Mac)
✅ Easy to read & write files
✅ Replace messy os.path
code
from pathlib import Path
p = Path("my_folder/my_file.txt")
🔹 Relative Path → "my_folder/my_file.txt"
🔹 Absolute Path → Path("/home/user/docs")
🔹 Current directory → Path.cwd()
🔹 Home directory → Path.home()
Let’s group them for easy learning 👇
Method / Property | Use |
---|---|
Path.cwd() |
Current working directory |
Path.home() |
Home directory |
Path(__file__).resolve() |
Absolute path of current script |
.resolve() |
Converts to absolute path |
.absolute() |
Absolute path (less strict than resolve ) |
.parent |
Get parent directory |
.parents |
All ancestors |
.name |
File name with extension |
.stem |
File name without extension |
.suffix |
File extension |
.suffixes |
List of multiple extensions |
.with_suffix(".csv") |
Change extension |
.with_name("new.txt") |
Change file name |
/ operator |
Join paths easily → Path("folder") / "file.txt" |
Method | What it does |
---|---|
.exists() |
Check if path exists |
.is_file() |
True if it’s a file |
.is_dir() |
True if it’s a directory |
.is_symlink() |
True if symbolic link |
.match("*.txt") |
Pattern match |
.samefile(other) |
Check if two paths point to same file |
Method | What it does |
---|---|
.mkdir(parents=True, exist_ok=True) |
Create directory |
.rmdir() |
Remove empty directory |
.iterdir() |
Iterate through directory contents |
.glob("*.txt") |
Match files by pattern |
.rglob("*.py") |
Recursive glob (search in all subfolders) |
Method | What it does |
---|---|
.read_text() |
Read text file |
.read_bytes() |
Read binary file |
.write_text("Hello") |
Write text to file |
.write_bytes(b"data") |
Write binary |
.open("mode") |
Open file (like built-in open() ) |
.unlink() |
Delete file |
.touch() |
Create empty file |
Method | Use |
---|---|
.stat() |
File metadata (size, modified time, etc.) |
.chmod(0o777) |
Change file permissions |
.rename("newname.txt") |
Rename file |
.replace("newpath.txt") |
Rename/replace |
.relative_to(other) |
Relative path |
.as_posix() |
Convert to POSIX string |
.as_uri() |
Convert to URI format |
from pathlib import Path
# Create a path
p = Path("example/test.txt")
# Check existence
if not p.exists():
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Hello Abhi 👋")
# Read it back
print(p.read_text()) # 👉 "Hello Abhi 👋"
# Change extension
new_p = p.with_suffix(".csv")
p.rename(new_p)
print("Renamed:", new_p)
📌 Pathlib = OOP way for files
🔹 Create & Navigate Paths → Path.cwd(), .home(), .parent
🔹 Check Paths → .exists(), .is_file(), .is_dir()
🔹 Directory Ops → .mkdir(), .rmdir(), .glob()
🔹 File Ops → .read_text(), .write_text(), .unlink()
🔹 Advanced → .stat(), .chmod(), .rename()
✨ Pro Tip:
Always prefer pathlib
over os.path
in modern Python projects.