Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

2 matches
Files & data easy

Compare Two Folder Structures and Find Differences in Python

Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.

filesystem os.walk comparison
Python
import os

def compare_folders(path1, path2):
    """
    Compare the file/folder structure of two directories and print differences.
    """
    def get_structure(root):
        structure = set()
        for dirpath, dirnames, filenames in os.walk(root):
            rel_path = os.path.relpath(dirpath, root)
         …
61 0 Open
Files & data easy

How to Compare Directory Trees in Python

This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.

filesystem comparison pathlib
Python
from pathlib import Path

def compare_directories(path1, path2):
    dir1 = Path(path1)
    dir2 = Path(path2)

    if not dir1.is_dir() or not dir2.is_dir():
        raise ValueError("Both paths must be directories.")

    files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
    files2 = {p.relative…
11 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.