Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Archive Old Files by Age in Python
Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.
import os
import shutil
import time
from pathlib import Path
def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
cutoff_time = time.time() - (days_old * 86400) # 86400 seconds in a day
archive_path = Path(archive_dir)
archive_path.mkdir(parents=True, exist_ok=True)
for i…
How to Check Disk Free Space in Python with shutil.disk_usage
This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.
import shutil
def check_disk_free_space(path="/"):
"""Return a tuple of total, used, and free disk space in bytes."""
usage = shutil.disk_usage(path)
return usage.total, usage.used, usage.free
if __name__ == "__main__":
total, used, free = check_disk_free_space()
print(f"Total: {total:,} bytes"…
How to Copy a File with shutil.copy2 in Python
Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.
import shutil
from pathlib import Path
source = Path("sample.txt")
destination = Path("sample_copy.txt")
source.write_text("Hello, PythonSkillset!")
if __name__ == "__main__":
shutil.copy2(source, destination)
copied = destination.read_text()
print(f"Copied content: {copied}")
print(f"Source exists:…
How to Sync Two Folders in Python (Lightweight Backup)
A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.
import os
import shutil
import sys
from pathlib import Path
def sync_folders(src: Path, dst: Path):
"""Sync src folder to dst folder, copying missing/updated files."""
dst.mkdir(parents=True, exist_ok=True)
for src_path in src.rglob("*"):
relative = src_path.relative_to(src)
dst_path = ds…
Move a file to an archive folder with shutil.move in Python
Move a file to an archive folder with shutil.move, creating the folder if needed, and return the new path.
from pathlib import Path
import shutil
def move_file_to_archive(source_file: str, archive_folder: str) -> Path:
"""Move a file to the archive folder, creating it if needed."""
src = Path(source_file)
archive = Path(archive_folder)
archive.mkdir(parents=True, exist_ok=True)
destination = archive / …
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.
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…
How to Auto Organize Downloads by File Extension in Python
A Python script that sorts files in a directory into subfolders based on their file extensions, creating folders automatically.
import os
import shutil
from pathlib import Path
def organize_downloads(download_dir="~/Downloads"):
"""Move files in a directory into subfolders based on file extension."""
download_path = Path(download_dir).expanduser()
if not download_path.exists():
print(f"Directory not found: {download_p…
How to Create a File Organizer That Sorts Files Automatically in Python
A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.
import os
import shutil
from pathlib import Path
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Video": [".mp4", ".mkv", ".avi", ".mov"],
"Archives": [".zip", ".tar", ".g…
How to Deploy a Static Site Build to an Nginx Directory in Python
Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.
import shutil
import os
from pathlib import Path
SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")
def deploy_site(src: Path, dest: Path) -> None:
if not src.exists():
raise FileNotFoundError(f"Build directory not found: {src}")
dest.mkdir(parents=True, exist_ok=True)
for item in src.ite…
How to Quarantine Suspicious Files in Python
Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.
import shutil
import os
from pathlib import Path
def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
"""
Move files with suspicious extensions to a quarantine folder.
Returns list of moved files.
"""
source_path = Path(source_dir)
quarantine_path = Path(quarantine_dir)
…
How to Recover Deleted .txt Files from a Backup in Python
A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.
import os
import shutil
from pathlib import Path
def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
"""Recover .txt files from backup directory."""
backup_path = Path(source_backup_dir)
dest_path = Path(destination_dir)
dest_path.mkdir(parents=True, exist_ok=True)
…
How to automatically organize your Downloads folder by file type in Python
This script scans the Downloads folder and moves files into sub-folders based on their extensions (e.g., Images, Documents, Videos).
import os
import shutil
from pathlib import Path
def organize_downloads_folder(downloads_path=None):
if downloads_path is None:
downloads_path = str(Path.home() / "Downloads")
if not os.path.exists(downloads_path):
print(f"Path {downloads_path} does not exist.")
return
fi…
Monitor Disk Usage and Alert in Python
A Python script that checks disk usage percentage against a threshold and returns an ALERT or OK message with free space details.
import shutil
import os
def check_disk_usage(path="/", threshold=85.0):
usage = shutil.disk_usage(path)
percent_used = (usage.used / usage.total) * 100
if percent_used > threshold:
return (f"ALERT: Disk usage at {percent_used:.1f}% on {path} "
f"(exceeds {threshold}% threshold…
Track File Changes with Version History in Python
A Python utility that monitors a file for changes, creating versioned backups with SHA-256 hashing to detect modifications and store a local JSON history.
import hashlib, json, os, shutil, time
from pathlib import Path
class FileTracker:
def __init__(self, history_file="file_history.json"):
self.history_file = Path(history_file)
self.history = self._load_history()
def _load_history(self):
if self.history_file.exists():
retur…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.