Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected
Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

12 matches
Sponsored Reserved space — layout preview until AdSense is connected
Files & data medium

Find Duplicate Web Pages by Content Similarity in Python

Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.

duplicate-detection hashing sha256
Python
import hashlib
import os
from collections import defaultdict

def get_file_hash(filepath):
    """Compute SHA-256 hash of file contents."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdiges…
2 0 Open
Files & data medium

Generate a Beautiful Folder Tree Visualization in Python

A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.

folder tree directory visualization
Python
import os
from pathlib import Path

class FolderTree:
    def __init__(self, root_path=".", ignore_list=None, max_depth=3):
        self.root = Path(root_path)
        self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
        self.max_depth = max_depth
        
    def generate(self):
        tree…
3 0 Open
Files & data medium

How to Generate an Inventory Report of All Files in Python

Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.

os.walk pathlib csv
Python
import os
import csv
from pathlib import Path
from datetime import datetime

def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
    headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
    rows = []
    start_time = datetime.now()
    
    for dirpath, dirna…
5 0 Open
Automation & scripting medium

Automatically Download the Latest Software Release from GitHub with Python

Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.

github api download
Python
import requests
import sys
from pathlib import Path

def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
    """Download the latest release asset from a GitHub repository."""
    url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
    response = requests.get(url)
    res…
2 0 Open
Automation & scripting medium

Detect Circular Imports Across Python Projects Automatically

This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.

circular-imports import-graph ast
Python
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque

def find_imports(filepath):
    """Return set of module names imported by a Python file."""
    imports = set()
    try:
        with open(filepath) as f:
            tree = ast.parse(f.read())
    except (SyntaxError, UnicodeDe…
2 0 Open
Automation & scripting medium

Detect and Remove Blurry Images in Python with OpenCV

Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.

opencv image-processing automation
Python
from pathlib import Path
import cv2
import numpy as np

def is_blurry(image_path, threshold=100.0):
    """
    Detect if an image is blurry using Laplacian variance.
    Returns True if blurry, False otherwise.
    """
    img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
    if img is None:
        return True…
6 0 Open
Automation & scripting medium

Find Orphan Files Not Referenced Anywhere in Python

Scan a project directory for files whose names never appear in the content of other files, identifying potentially unused resources.

orphan files file cleanup automation
Python
import os
from pathlib import Path
import re

def find_orphan_files(root_dir: str, extensions: set = None, ignore_patterns: list = None):
    """Find files not referenced by any other file in the project."""
    if extensions is None:
        extensions = {'.txt', '.md', '.py', '.html', '.css', '.js', '.json', '.yaml'…
4 0 Open
Automation & scripting medium

Find and Delete Duplicate Files Using Hashing in Python

Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.

deduplication files hashing
Python
import hashlib
import os
from pathlib import Path

def file_hash(path, block_size=65536):
    """Return SHA256 hash of file content."""
    hasher = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(block_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_and_d…
5 0 Open
Automation & scripting medium

Find the Largest Files Consuming Disk Space with a Beautiful Terminal Report in Python

Scan a directory recursively and print a formatted terminal report of the largest files, with human-readable sizes.

file-system disk-space pathlib
Python
import os
import sys
from pathlib import Path

def get_largest_files(directory: str, count: int = 10) -> list:
    """
    Scan the given directory and return the largest files.
    
    Args:
        directory: Path to the directory to scan
        count: Number of largest files to return
        
    Returns:
      …
4 0 Open
Automation & scripting medium

How to Generate Project Statistics Including Lines of Code and Complexity in Python

Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.

code metrics lines of code cyclomatic complexity
Python
import os
from pathlib import Path

def count_lines_of_code(filepath):
    """Counts lines of code in a Python file, excluding blank lines and comments."""
    try:
        with open(filepath, 'r') as f:
            lines = f.readlines()
        code_lines = [line for line in lines if line.strip() and not line.strip()…
4 0 Open
Automation & scripting medium

How to Generate a Dependency Graph for Python Projects

This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.

ast dependency graph import parsing
Python
import os
import ast
from pathlib import Path
from collections import defaultdict

def get_imports(filepath):
    with open(filepath) as f:
        try:
            tree = ast.parse(f.read())
        except SyntaxError:
            return []
    imports = []
    for node in ast.walk(tree):
        if isinstance(node, …
2 0 Open
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
3 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.