Reference library

Files & data

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

58 matches
Files & data easy

How to Walk a Directory Tree with os.walk in Python

A generator function that recursively walks a directory tree and yields every file path found using the os.walk generator.

os.walk generators directory-tree
Python
import os


def walk_directory_tree(root_path: str):
    """Walk a directory tree and yield file paths using os.walk generator."""
    for dirpath, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
            yield os.path.join(dirpath, filename)


if __name__ == "__main__":
    # Create a…
12 0 Open
Files & data easy

How to Watch a Directory for New Files in Python

Poll a directory at regular intervals and detect newly added files, printing each one as it appears.

file watching polling os.listdir
Python
import time
import os
from pathlib import Path

WATCH_DIR = Path("watched_files")

def watch_for_new_files(directory: Path, sleep_time: float = 1.0, max_iterations: int = 10):
    """Poll a directory for new files and print when one appears."""
    directory.mkdir(exist_ok=True)
    existing = set(os.listdir(directory…
12 0 Open
Files & data medium

How to Write a List of Lines to a Text File Safely in Python

This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.

files atomic-write pathlib
Python
from pathlib import Path
import tempfile
import os

def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
    """Write lines to a text file atomically to avoid corruption."""
    path = Path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    
    fd, temp_path = tempfile.mkstemp(dir=str…
13 0 Open
Files & data easy

How to check file data in Python

Check if a file exists and is a regular file, then return its name, size, line count, and first line.

file pathlib metadata
Python
def check_file_data(file_path):
    from pathlib import Path
    path = Path(file_path)
    if not path.exists():
        return f"File '{file_path}' does not exist."
    if not path.is_file():
        return f"'{file_path}' is not a regular file."
    
    size = path.stat().st_size
    lines = path.read_text(encodin…
15 0 Open
Files & data easy

How to resolve a symlink to its real path in Python with pathlib

Use Path.resolve() to turn a symlink path into its absolute target path, handling relative symlinks and eliminating symbolic links.

pathlib symlink filesystem
Python
from pathlib import Path

def resolve_symlink(path):
    p = Path(path)
    return str(p.resolve())

if __name__ == "__main__":
    # Create a symlink to demonstrate the resolution
    target = Path("/tmp/real_target.txt")
    target.write_text("hello")
    link = Path("/tmp/my_link.txt")
    try:
        link.symlink…
14 0 Open
Files & data easy

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.

shutil pathlib file-move
Python
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 / …
12 0 Open
Files & data easy

Reassemble File Parts into Original File Bytes in Python

Read sorted part files from a directory and concatenate their bytes into the original file.

file handling binary byte concatenation
Python
import os
import sys
from pathlib import Path

def reassemble_parts(parts_dir: Path, output_path: Path) -> int:
    """
    Reassemble file parts into the original file.

    Args:
        parts_dir: Directory containing the part files
        output_path: Path where the reassembled file will be written

    Returns:
…
12 0 Open
Files & data easy

Rotate Log Files in Python by Size

This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.

log-rotation files os
Python
import os
import glob
from pathlib import Path

def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
    log_file = Path(log_path)
    if log_file.stat().st_size <= max_size_bytes:
        print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
        return

    for i in range(max_backu…
13 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
Files & data easy

Write CSV file with csv DictWriter in Python

Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.

csv file-writing dictwriter
Python
import csv
from pathlib import Path

fieldnames = ["name", "city", "age"]
rows = [
    {"name": "Alice", "city": "New York", "age": 30},
    {"name": "Bob", "city": "Los Angeles", "age": 25},
    {"name": "Charlie", "city": "Chicago", "age": 35},
]

path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
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.