Pathlib Cheat Sheet


pathlib is a Python module introduced in Python 3.4 (2014) by Antoine Pitrou.
It provides an object-oriented interface to work with filesystem paths,
making code more readable and intuitive compared to traditional os.path functions.

 

Cross-platform compatibility note
pathlib handles differences in path separators (/ vs \) automatically, making scripts more portable between operating systems.

 

 

from pathlib import Path



In the top of your Python script: 
from pathlib import Path

 

 

Content

 

 

 

Creating a Path object (Python object)

p = Path("my_folder/file.txt")
print(p)
my_folder/file.txt

 

 

Type of a Path object

print(type(file_path))
<class 'pathlib.WindowsPath'>

 

 

Current working directory

print(Path.cwd())
C:\Users\jaime\Desktop

 

 

Joining paths with the / operator

base = Path("my_folder")
file_path = base / "subfolder" / "file.txt"
print(file_path)
my_folder\subfolder\file.txt

 

 

Resolving and getting absolute paths

p = Path("my_folder/file.txt")
print(p.resolve())
print(p.absolute())
C:\Users\jaime\Desktop\my_folder\file.txt
C:\Users\jaime\Desktop\my_folder\file.txt

 

 

Accessing parent directories, name, stem, and suffix

p = Path("/home/user/my_folder/file.txt")
print(p.parent)      
print(p.parents[0])  
print(p.parents[1])  
print(p.name)        
print(p.stem)        
print(p.suffix)
\home\user\my_folder
\home\user\my_folder
\home\user
file.txt
file
.txt

 

 

User home directory

home = Path.home()
print(home)
C:\Users\jaime

 

 

Expanding ~ to the user home directory

file_path = Path("~/documents/file.txt").expanduser()
print(file_path)
C:\Users\jaime\documents\file.txt

 

 





Assume:

from pathlib import Path

file_path = Path("example.txt")
folder_path = Path("my_folder")
link_path = Path("link_to_example")

 

 

Check existence

print("File exists?", file_path.exists())
print("Folder exists?", folder_path.exists())
print("Link exists?", link_path.exists())
File exists? True
Folder exists? True
Link exists? True

 

 

Check type

print("Is file?", file_path.is_file())
print("Is directory?", file_path.is_dir())

print("Folder is directory?", folder_path.is_dir())
print("Folder is file?", folder_path.is_file())

print("Link is symlink?", link_path.is_symlink())
Is file? True
Is directory? False
Folder is directory? True
Folder is file? False
Link is symlink? True

 

 

File information

info = file_path.stat()
print("File size (bytes):", info.st_size)
print("Last modification:", info.st_mtime)
print("Last access:", info.st_atime)
File size (bytes): 14
Last modification: 1759656090.213048
Last access: 1759656090.213048

Note: Timestamps in epoch format

 

 

Creating and writing a file

if not file_path.exists():
    file_path.write_text("Test content\n")

 

 

Creating a folder

if not folder_path.exists():
    folder_path.mkdir()

 

 


Python