Working with files is only half the story — you also need to move around the folders (directories) that contain them. Python gives you several tools for creating, checking, moving, and deleting directories. The most modern and beginner-friendly option is the pathlib module, which makes dealing with paths much easier than the older os functions. Let’s walk through how to use it.
Why use pathlib?
In the past, file paths were just strings like "C:\\Users\\Alex\\Docs" on Windows or "/home/alex/docs" on Linux. This quickly got messy because of different path separators (\ vs /). The pathlib module solves this by giving you Path objects that handle all the operating system quirks for you. You don’t need to think about slashes or escaping backslashes anymore.
from pathlib import Path
cwd = Path.cwd() # Current working directory
home = Path.home() # Home directory
docs = home / "Documents" / "Python" # Join paths easily
print(cwd, home, docs)
Here, the / operator builds new paths cleanly, regardless of your platform.
Try this:
- Print your current working directory with
Path.cwd(). - Build a path to a
projects/testfolder inside your home directory.
Windows vs Linux paths
Operating systems don’t agree on how paths should look:
- Linux/macOS:
/home/alex/docs(forward slashes, no drive letters). - Windows:
C:\Users\Alex\Docs(backslashes, drive letters).
If you hard-code paths, your code might break on another machine. pathlib saves you by choosing the correct style automatically.
from pathlib import Path
linux_style = Path("/var/log")
windows_style = Path(r"C:\Users\Alex\Docs")
portable = Path("data") / "images"
On Linux, the above prints PosixPath, while on Windows it prints WindowsPath. Same code, different outputs — and you didn’t have to change anything.
Try this:
- Build a nested path with
/and print.resolve()to see the absolute version. - On Windows, experiment with raw strings
r"C:\Temp"vs"C:\\Temp".
Creating directories
If you want to create folders, use mkdir. The parents=True option tells Python to create any missing parent folders, and exist_ok=True prevents errors if the folder already exists.
from pathlib import Path
reports = Path("reports/2025/09")
try:
reports.mkdir(parents=True, exist_ok=True)
print("Created or already existed:", reports)
except PermissionError:
print("You don’t have permission here.")
Without these flags, you’ll get errors if the folder exists already or if the path is incomplete.
Try this:
- Create a folder structure like
logs/2025/sepin one call. - Remove
exist_ok=Trueand run it twice to see the error.
Listing what’s inside a directory
Once a folder exists, you’ll probably want to see what’s in it.
iterdir()shows all items inside.glob(pattern)finds items matching a pattern.rglob(pattern)does the same, but searches all subfolders too.
from pathlib import Path
base = Path("reports")
for item in base.iterdir():
print("Item:", item, "Directory?", item.is_dir())
for csv in base.glob("*.csv"):
print("CSV file:", csv)
for deep_csv in base.rglob("*.csv"):
print("Deep CSV:", deep_csv)
Try this:
- Count how many
.txtfiles are in a folder. - Print only the names (not paths) with
.name.
Changing directories
Python scripts normally run in a “current working directory”. You can change it with os.chdir, but it’s often better to avoid changing directories and instead build full paths with pathlib.
import os
from pathlib import Path
print("Before:", Path.cwd())
os.chdir(Path.home())
print("After:", Path.cwd())
If you rely on chdir, your code depends on where you last pointed it. Using Path objects keeps things predictable.
Try this:
- Change to your home directory and back again.
- Rewrite the code without
chdir, using absolute paths instead.
Deleting directories
When it’s time to tidy up:
Path.rmdir()removes empty folders.shutil.rmtree()removes folders and everything inside them — use carefully!
from pathlib import Path
import shutil
temp = Path("temp/empty")
temp.mkdir(parents=True, exist_ok=True)
try:
temp.rmdir()
print("Removed empty folder.")
except OSError:
print("Folder not empty.")
shutil.rmtree("temp/full_project") # deletes everything inside
Try this:
- Create a folder, add a file, then try deleting it with
rmdir()(it will fail). - Use
shutil.rmtreeto delete it fully.
Useful checks and helpers
Before working with a path, it’s wise to check what it actually is.
from pathlib import Path
p = Path("reports/../reports/2025/09")
print("Resolved:", p.resolve())
print("Exists?", p.exists())
print("Is file?", p.is_file())
print("Is directory?", p.is_dir())
This makes sure your code behaves as expected before acting on paths.
Try this:
- Write a function that takes a folder path and lists only
.csvfiles. - Test it with both existing and missing folders to see the difference.
Wrap-up
- Use
pathlibfor clear, cross-platform paths. mkdirbuilds folders,iterdirandgloblist them.- Avoid
chdirwhen possible; prefer absolute paths. - Use
rmdirfor empty folders,shutil.rmtreefor full ones. - Handle common errors like
PermissionError,FileNotFoundError, andOSError.
With these tools, you can create, explore, and remove directories confidently on Windows, Linux, or macOS without worrying about slashes or surprises.







