Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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.
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…
Automatically Detect Corrupted Files Using SHA-256 Checksums in Python
Compute SHA-256 checksums of files and compare them to detect corruption in 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…
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.
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…
Build a Command-Line To-Do List Application with Data Persistence in Python
A persistent command-line to-do list that saves tasks as JSON, supporting add, show, toggle done, and quit commands.
import json
import os
TODO_FILE = "todos.json"
def load_todos():
if not os.path.exists(TODO_FILE):
return []
with open(TODO_FILE, "r") as f:
return json.load(f)
def save_todos(todos):
with open(TODO_FILE, "w") as f:
json.dump(todos, f, indent=2)
def show_todos(todos):
if not…
Build a Personal Work Hours Tracker in Python
A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.
import csv
from pathlib import Path
from datetime import datetime, date
class WorkHoursTracker:
def __init__(self, file_path="work_hours.csv"):
self.file_path = Path(file_path)
if not self.file_path.exists():
with open(self.file_path, "w", newline="") as f:
writer = csv…
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.
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:
…
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.
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…
Calculate Working Hours Between Two Dates in Python
Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.
from datetime import datetime, timedelta
def work_hours_between(start: datetime, end: datetime) -> float:
"""Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
def is_workday(d: datetime) -> bool:
return d.weekday() < 5
total_hours = 0.0
current = start
whi…
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.
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)
…
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.
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…
Convert All Markdown Files in a Folder to HTML in Python
Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.
import os
import markdown
from pathlib import Path
def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
input_path = Path(input_folder)
output_path = Path(output_folder)
output_path.mkdir(exist_ok=True)
for md_file in input_path.glob("*.md"):
with open…
Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
import csv
import json
def csv_to_json(csv_filepath, json_filepath):
"""Convert a CSV file to a JSON file."""
with open(csv_filepath, mode='r', newline='') as csv_file:
reader = csv.DictReader(csv_file)
data = [row for row in reader]
with open(json_filepath, mode='w') as json_file:
…
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.
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((…
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.
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.…
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.
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)
…
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.
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…
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.
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…
Download Files from Internet with Progress Bar in Python
Download a file from the internet while displaying a text progress bar in the terminal.
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 …
Encrypt and Decrypt Files Using Python
Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.
import os
from pathlib import Path
from cryptography.fernet import Fernet
def generate_key(key_file: Path) -> bytes:
key = Fernet.generate_key()
key_file.write_bytes(key)
return key
def load_key(key_file: Path) -> bytes:
return key_file.read_bytes()
def encrypt_file(input_path: Path, key: bytes, out…
Extract Hyperlinks from Word Documents in Python
Parses a .docx file using Python's standard library to extract every hyperlink's display text and target URL.
import zipfile
from pathlib import Path
import xml.etree.ElementTree as ET
def extract_hyperlinks_from_docx(filepath: str) -> list[dict]:
"""
Extract all hyperlinks from a .docx file.
Returns a list of dicts with 'text' and 'target' keys.
"""
hyperlinks = []
with zipfile.ZipFile(Path(filepath)…
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.
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…
Generate Timesheet Reports from Daily Logs in Python
Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.
import json
from pathlib import Path
from collections import defaultdict
def generate_timesheet_report(daily_logs: list[dict]) -> str:
"""
Generate a timesheet report from daily log entries.
Args:
daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
Returns:
…
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.
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…
Generate a Monthly Calendar PDF in Python
Create a Python utility that generates a monthly calendar PDF using ReportLab, with weekday headers and day numbers laid out in a grid.
from calendar import TextCalendar
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os
def generate_monthly_calendar_pdf(year, month, filename="calendar.pdf"):
cal = TextCalendar()
days = cal.monthdays2calendar(year, month)
month_name …
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.