Reference library

Files & data

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

4 matches
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

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

How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

hashlib sha256 file-hash
Python
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_fi…
16 0 Open
Files & data easy

Sync only changed files between two folders in Python

This code compares two folders and copies only the new or modified files from source to destination, skipping unchanged ones by comparing SHA-256 hashes.

files sync hashing
Python
import hashlib
from pathlib import Path
import shutil

def file_hash(path: Path, chunk_size: int = 8192) -> str:
    hasher = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def sync_files(src: s…
16 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.