Navigating Directories in Python

A cartoon owl stands at a crossroads holding a map. Signposts point to Linux (/home/), Windows (C:\Users), and Reports. Above, bold text reads “Navigating Directories in Python.”

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.

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/test folder 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.

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/sep in one call.
  • Remove exist_ok=True and 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.

Try this:

  • Count how many .txt files 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.

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!

Try this:

  • Create a folder, add a file, then try deleting it with rmdir() (it will fail).
  • Use shutil.rmtree to delete it fully.

Useful checks and helpers

Before working with a path, it’s wise to check what it actually is.

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 .csv files.
  • Test it with both existing and missing folders to see the difference.

Wrap-up

  • Use pathlib for clear, cross-platform paths.
  • mkdir builds folders, iterdir and glob list them.
  • Avoid chdir when possible; prefer absolute paths.
  • Use rmdir for empty folders, shutil.rmtree for full ones.
  • Handle common errors like PermissionError, FileNotFoundError, and OSError.

With these tools, you can create, explore, and remove directories confidently on Windows, Linux, or macOS without worrying about slashes or surprises.

Main Topic

Python Files and Directories

A cartoon owl with wide eyes stands in front of grey filing cabinets. One drawer is open, filled with folders, and the owl is holding a single document. The background is a warm orange tone, and the words “PYTHON FILES” appear in large bold text above the cabinets.

A light-hearted intro to handling files and directories in Python, featuring an owl mascot and fun “Python Files” imagery.

Other Tutorials in this Topic

A cartoon owl shrugs at a table with three letters: one in English, one in Arabic, and one in Chinese. Above it, bold text reads “CHARACTER ENCODINGS.”

Reading different Character Sets

This tutorial explains character encodings, why they exist, handling decoding errors, platform newline differences, and reading binary…

A cartoon owl with wide eyes stands against an orange background, holding and reading a letter. Above it, bold text reads “READING FILES IN PYTHON.”

Reading Files in Python

This tutorial teaches how to safely open and read files in Python, explore different reading methods, and…

A cheerful cartoon owl writes in an open notebook with a quill pen beside a filing cabinet drawer labelled “w, a, x.” Above, bold text reads “Writing Files in Python.”

Writing to Files in Python

Part 1 introduces writing to files in Python using context managers, explains file modes w, a, x,…

A cartoon owl sits at a desk holding two papers. One shows “Café 😊” clearly, the other displays scrambled symbols. Behind, a chalkboard reads “Character Encoding.”

Writing different Character Sets

This tutorial explains character encoding, why encodings differ, handling Unicode errors, appending safely, and using safer update…

A cartoon owl takes a document from a filing cabinet and drops it into a bin. Above, bold text reads “File Operations.”

Renaming and Deleting Files in Python

This tutorial covers renaming, moving, and deleting files in Python using pathlib, with examples, common exceptions, and…

A cartoon owl stands in front of a bookshelf, holding an old book while placing a new one on the shelf. Above, bold text reads “File Operations.”

More Python File Operations

This tutorial explores safer file operations, including overwriting with os.replace, moving across drives, creating backups, soft deletes,…