Reference library

Files & data

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

109 matches
Files & data easy

Audit File Permissions Across a Project in Python

Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.

file permissions os.walk audit
Python
import os
import stat
from pathlib import Path

def audit_file_permissions(project_root):
    """Walk through project_root and print path, owner, and permissions for every file."""
    results = []
    for root, dirs, files in os.walk(project_root):
        for name in files + dirs:
            full_path = os.path.joi…
56 0 Open
Files & data easy

Automatically Detect Corrupted Files Using SHA-256 Checksums in Python

Compute SHA-256 checksums of files and compare them to detect corruption in Python.

checksum file-integrity hashlib
Python
import hashlib
import os

def compute_sha256(filepath: str) -> str:
    """Compute SHA-256 checksum of a file."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdigest()

def validate_file_int…
57 1 Open
Files & data easy

Automatically Highlight Data Validation Errors Inside Excel Files in Python

Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.

excel validation openpyxl
Python
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path

def highlight_validation_errors(filepath: str, output_path: str = None):
    wb = openpyxl.load_workbook(filepath)
    red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
    
    for sheet in wb.worksheet…
60 0 Open
Files & data easy

Build a File Index by Relative Path Hash Map in Python

Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.

os.walk file-index defaultdict
Python
import os
from collections import defaultdict


def build_file_index(root_dir):
    index = defaultdict(list)

    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            full_path = os.path.join(dirpath, filename)
            relative_path = os.path.relpath(full_path, roo…
19 0 Open
Files & data easy

Build a Python Script That Detects and Deletes Empty Files Across Folders

A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.

filesystem cleanup pathlib
Python
import os
from pathlib import Path

def find_and_delete_empty_files(root_dir: str) -> list:
    """Find and delete all empty files under root_dir. Returns list of deleted paths."""
    deleted = []
    for file_path in Path(root_dir).rglob('*'):
        if file_path.is_file() and file_path.stat().st_size == 0:
       …
57 0 Open
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
50 0 Open
Files & data easy

Build a Simple ETL Pipeline in Python

A simple ETL pipeline that reads JSON Lines, transforms records with filtering and normalization, and writes the result to JSON.

etl json jsonl
Python
import json
from pathlib import Path


def read_input(file_path: Path) -> list[dict]:
    """Read JSON lines file into list of dicts."""
    with file_path.open("r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def transform(records: list[dict]) -> list[dict]:
    """Transf…
13 0 Open
Files & data medium

Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

file i/o chunking hashing
Python
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """S…
15 0 Open
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

Compress and Extract ZIP Files Programmatically in Python

Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.

zip compression file-io
Python
import zipfile
from pathlib import Path
import tempfile
import os

def create_sample_zip(zip_path: str, files: dict) -> None:
    """Create a ZIP file containing the given files (name -> content mapping)."""
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for filename, content in files.ite…
99 0 Open
Files & data easy

Convert File Data to a Dictionary in Python

This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.

file-metadata pathlib directory
Python
from pathlib import Path

def convert_files_data(directory: str) -> dict:
    data = {}
    base = Path(directory)
    if not base.exists():
        return data
    for file in base.iterdir():
        if file.is_file():
            data[file.name] = {
                "size": file.stat().st_size,
                "exten…
15 0 Open
Files & data medium

Convert Image to ASCII Art in Python

Convert any image to ASCII art by resizing, converting to grayscale, and mapping pixel brightness to characters using Pillow.

image ascii-art pillow
Python
from PIL import Image
import sys

ASCII_CHARS = "@%#*+=-:. "

def resize_image(image, new_width=100):
    """Resize image maintaining aspect ratio."""
    width, height = image.size
    ratio = height / width
    new_height = int(new_width * ratio * 0.55)  # 0.55 adjusts for font aspect ratio
    return image.resize((…
51 0 Open
Files & data easy

Count Files by Extension in Python

Count files in a directory grouped by file extension using Python's standard library.

files pathlib directory
Python
from pathlib import Path

def count_files_by_extension(directory: str) -> dict[str, int]:
    """Count files in a directory grouped by file extension."""
    data = {}
    for path in Path(directory).iterdir():
        if path.is_file():
            ext = path.suffix.lower() or "(no extension)"
            data[ext] =…
14 0 Open
Files & data medium

Create a Local File Versioning System Using Pure Python

Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.

file-versioning files backup
Python
import os
import shutil
import hashlib
import json
import time
from pathlib import Path

class LocalFileVersioning:
    def __init__(self, target_dir="versioned_files", versions_dir="versions"):
        self.target_dir = Path(target_dir)
        self.versions_dir = Path(versions_dir)
        self.metadata_file = self.…
53 0 Open
Files & data easy

Create a Personal Knowledge Base That Searches Notes Instantly in Python

Build a lightweight personal knowledge base with JSON storage and instant case-insensitive full-text search across note titles and content.

json knowledge base search
Python
import json
import re
import sys

class PersonalKnowledgeBase:
    def __init__(self, file_path="kb_notes.json"):
        self.file_path = file_path
        self.notes = self._load_notes()

    def _load_notes(self):
        try:
            with open(self.file_path, "r") as f:
                return json.load(f)
    …
55 0 Open
Files & data medium

Create a Python Tool That Generates Professional Excel Dashboards

Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.

openpyxl excel dashboard
Python
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

def create_sales_dashboard(workbook_path: str) -> None:
    """Generate a professional sales dashboard in an Excel workbook."""
    wb = op…
49 0 Open
Files & data medium

Create a ZIP Archive of a Folder in Python

Recursively zip all files in a folder into a single archive using the standard library zipfile and pathlib modules.

zipfile pathlib archives
Python
import zipfile
from pathlib import Path

def zip_folder(source_dir: str, archive_path: str) -> None:
    """Zip all files in source_dir recursively into archive_path."""
    source = Path(source_dir)
    with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as archive:
        for file_path in source.rglob("*"…
16 0 Open
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 0 Open
Files & data easy

Detect Outliers in CSV Data Using Z-Score in Python

Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.

outlier-detection z-score csv
Python
import csv
import statistics
from math import sqrt

def detect_outliers(csv_path, column_name, threshold=2.0):
    """Detect outliers in a numeric column using z-score method."""
    values = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        if column_name not in reader.field…
51 0 Open
Files & data medium

Download Files from Internet with Progress Bar in Python

Download a file from the internet while displaying a text progress bar in the terminal.

urllib download progress bar
Python
import urllib.request
import sys

def download_with_progress(url, filename):
    """Download a file with a simple text progress bar."""
    def report_hook(block_count, block_size, total_size):
        downloaded = block_count * block_size
        if total_size > 0:
            percent = min(100, int(downloaded * 100 …
54 0 Open
Files & data easy

Export List of Dicts to CSV in Python

Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.

csv export dictwriter
Python
import csv

def export_to_csv(data, filename):
    """Export a list of dicts to a CSV file."""
    if not data:
        print("No data to export")
        return
    
    # Get column names from the keys of the first dict
    fieldnames = list(data[0].keys())
    
    with open(filename, 'w', newline='', encoding='utf…
14 0 Open
Files & data easy

Export SQLite Query Results to CSV in Python

Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.

sqlite csv export
Python
import sqlite3
import csv

def export_query_to_csv(db_path, query, csv_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(query)

    rows = cursor.fetchall()
    column_names = [description[0] for description in cursor.description]

    with open(csv_path, 'w', newline='', encodi…
17 0 Open
Files & data easy

Extract a Single Member from a ZIP Archive in Python

Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.

zipfile zip extraction
Python
import zipfile
from pathlib import Path

def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
    """Extract a single member from a zip archive to the output directory."""
    with zipfile.ZipFile(zip_path, "r") as archive:
        archive.extract(member_name, output_dir)
    retu…
19 0 Open
Files & data easy

File Data Helper Functions in Python

Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.

file-io pathlib json
Python
from pathlib import Path

def load_text_file(filepath):
    """Read a text file and return its contents as a string."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")
    return path.read_text(encoding="utf-8")

def save_text_file(filepath, content):
…
14 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.