Reference library

Files & data

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

84 matches
Files & data easy

How to Convert Images Between Formats in Python

Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.

pillow image conversion file i/o
Python
from PIL import Image
import sys

def convert_image_format(input_path, output_path):
    try:
        img = Image.open(input_path)
        img.save(output_path)
        print(f"Converted {input_path} to {output_path}")
    except FileNotFoundError:
        print(f"Error: File {input_path} not found")
        sys.exit(…
41 0 Open
Files & data easy

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.

shutil file-copy pathlib
Python
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:…
11 0 Open
Files & data easy

How to Create Nested Directories with pathlib mkdir parents in Python

Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.

pathlib mkdir directories
Python
from pathlib import Path

def create_nested_directories(base_path: str, dirs: list[str]) -> None:
    for directory in dirs:
        path = Path(base_path) / directory
        path.mkdir(parents=True, exist_ok=True)
        print(f"Created: {path}")

if __name__ == "__main__":
    root = "output"
    nested_dirs = ["2…
13 0 Open
Files & data easy

How to Decompress a gzip File in Python

This code provides a function to decompress a .gz file, writing the decompressed content to a new file and returning the text, using the gzip standard library module.

gzip decompression file-handling
Python
import gzip
from pathlib import Path

def decompress_gzip(filepath: str, output_path: str | None = None) -> str:
    """Decompress a .gz file and return the decompressed content."""
    input_path = Path(filepath)
    if output_path is None:
        output_path = str(input_path.with_suffix(""))
    
    with gzip.open…
12 0 Open
Files & data easy

How to Delete a File if it Exists in Python

Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.

pathlib file-deletion file-management
Python
from pathlib import Path

def delete_file_if_exists(file_path: str) -> bool:
    """Delete a file if it exists. Returns True if deleted, False if not found."""
    path = Path(file_path)
    if path.exists():
        path.unlink()
        print(f"Deleted: {path}")
        return True
    else:
        print(f"File not…
14 0 Open
Files & data easy

How to Detect File Encoding: UTF-8 vs Latin-1 in Python

Detect whether a file is UTF-8 or Latin-1 encoded by attempting a UTF-8 decode and falling back to Latin-1.

file-encoding utf-8 latin-1
Python
import sys

def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        raw = f.read()
    
    try:
        raw.decode('utf-8')
        return 'UTF-8'
    except UnicodeDecodeError:
        return 'latin1'

if __name__ == "__main__":
    file_path = sys.argv[1] if len(sys.argv) > 1 else 'sample.txt'
…
13 0 Open
Files & data easy

How to Extract IP Address Counts from Access Logs in Python

Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.

regex access log counter
Python
import re
from collections import Counter
from pathlib import Path

def extract_ip_counts(log_file_path):
    ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    ip_counter = Counter()
    
    with open(log_file_path, 'r') as file:
        for line in file:
            match = re.match(ip_pattern, line)
       …
17 0 Open
Files & data easy

How to Extract Text from PDF Files in Python

Extract all readable text from a PDF file using PyPDF2, iterating over each page and concatenating the content.

pdf text-extraction pypdf2
Python
import PyPDF2

def extract_text_from_pdf(pdf_path):
    text = ""
    with open(pdf_path, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text.strip()

if __name__ == "__main__":
    pdf_path = "sample.pdf"
    extracted…
53 0 Open
Files & data easy

How to Filter CSV Rows by Column Value in Python

Filter CSV rows based on a column value condition using the standard csv module and a lambda function.

csv filter file-io
Python
import csv

def filter_csv(input_file, output_file, column, condition):
    with open(input_file, newline='', encoding='utf-8') as infile, \
         open(output_file, 'w', newline='', encoding='utf-8') as outfile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames
        writer = csv.Dict…
19 0 Open
Files & data easy

How to Filter Files by Extension and Size in Python

Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.

pathlib filesystem filtering
Python
from pathlib import Path

def filter_files_by_extension(directory: str, extension: str) -> list:
    """Return a list of file names in directory with the given extension."""
    path = Path(directory)
    return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]

def filter_files_by_size(directo…
13 0 Open
Files & data easy

How to Find Files by Extension in Python

This code walks a directory tree with pathlib, collects all file paths, and counts them by extension to summarize a project's contents.

pathlib file-system recursion
Python
from pathlib import Path

def get_project_files(base_path="."):
    """Return a sorted list of all file paths under base_path."""
    base = Path(base_path)
    files = [p for p in base.rglob("*") if p.is_file()]
    return sorted(files)

def count_by_extension(files):
    """Return a dict mapping extension (lowercase…
12 0 Open
Files & data easy

How to Group Files by Extension in Python

Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.

pathlib grouping filesystem
Python
from pathlib import Path


def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
    """Group file names by their extension."""
    grouped: dict[str, list[str]] = {}
    for file in files:
        ext = file.suffix.lower()
        grouped.setdefault(ext, []).append(file.name)
    return grouped


if…
14 0 Open
Files & data easy

How to Handle Missing Values in a CSV Numeric Column in Python

Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.

csv data-cleaning statistics
Python
import csv
from pathlib import Path
import statistics

def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
    """
    Handles missing values in a numeric column of a CSV file.
    Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
    """
    row…
12 0 Open
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 0 Open
Files & data easy

How to List File Metadata in Python

This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.

pathlib file-metadata filesystem
Python
from pathlib import Path
import json

def format_files_data(directory_path):
    """Return a list of JSON-serializable dicts with file metadata."""
    base = Path(directory_path)
    if not base.is_dir():
        raise ValueError(f"Not a directory: {directory_path}")

    files_data = []
    for file_path in base.ite…
12 0 Open
Files & data easy

How to List Files Matching a Glob Pattern in Python

Uses pathlib.Path.glob to find and sort all files matching a glob pattern like *.py in a directory.

glob pathlib filesystem
Python
from pathlib import Path

def list_files_matching(pattern: str, directory: str = ".") -> list[str]:
    """Return sorted list of file paths matching the glob pattern in a directory."""
    return sorted(Path(directory).glob(pattern))

if __name__ == "__main__":
    # Example: list all .py files in current directory
  …
12 0 Open
Files & data easy

How to List Tar Archive Contents in Python

Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.

tarfile archive filesystem
Python
import tarfile
from pathlib import Path

def list_tar_contents(archive_path):
    """List all entries in a tar archive."""
    entries = []
    with tarfile.open(archive_path, "r") as tar:
        for member in tar.getmembers():
            entry_type = "dir" if member.isdir() else "file"
            entries.append(f"…
12 0 Open
Files & data easy

How to Load a YAML Subset in Python Without PyYAML

Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.

yaml parsing stdlib
Python
import re
from pathlib import Path

def load_yaml_subset(path):
    """Load a flat YAML file (key: value) without external dependencies."""
    data = {}
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            # Skip empty lines and comments
            line = line.strip()
            if no…
18 0 Open
Files & data easy

How to Load and Save JSON Files in Python

Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.

json files pathlib
Python
import json
from pathlib import Path


def load_json(filepath: str) -> dict:
    """Load JSON data from a file."""
    path = Path(filepath)
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def save_json(filepath: str, data: dict) -> None:
    """Save data to a JSON file with pretty format…
11 0 Open
Files & data easy

How to Merge Dicts from Two JSON Files Like a Pro

This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.

json dict merge
Python
import json
from pathlib import Path


def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
    """Merge two JSON files containing dicts, with file2 overriding file1."""
    data1 = json.loads(Path(file1).read_text())
    data2 = json.loads(Path(file2).read_text())

    merged = {**data1,…
13 0 Open
Files & data easy

How to Parse INI Config Files in Python with configparser

Load and read settings from an INI file using Python's built-in configparser module, with type-safe value access.

configparser ini configuration
Python
import configparser
from pathlib import Path

# Create a sample INI file for demonstration
sample_content = """
[Database]
host = localhost
port = 5432
user = admin
password = secret123

[Logging]
level = INFO
file = app.log
max_size = 10MB
"""

config_file = Path("sample_config.ini")
config_file.write_text(sample_con…
12 0 Open
Files & data easy

How to Parse JSON, TXT, and CSV Files in Python

This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.

json csv file parsing
Python
import json
from pathlib import Path

def parse_json_file(filepath):
    """Read and parse a JSON file, returning its contents."""
    path = Path(filepath)
    with path.open('r', encoding='utf-8') as f:
        return json.load(f)

def parse_txt_lines(filepath):
    """Read a text file and return non-empty stripped …
15 0 Open
Files & data easy

How to Parse NDJSON Lines into a List in Python

Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.

json ndjson file-io
Python
import json
from pathlib import Path


def parse_ndjson(file_path: str) -> list:
    data = []
    with Path(file_path).open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                data.append(json.loads(line))
    return data


if __name__ == "__main__"…
12 0 Open
Files & data easy

How to Parse Path Components with pathlib Path in Python

Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.

pathlib filesystem file-paths
Python
from pathlib import Path

if __name__ == "__main__":
    p = Path("data/reports/2024/final.txt")
    print(f"Path: {p}")
    print(f"Parent: {p.parent}")
    print(f"Name: {p.name}")
    print(f"Stem: {p.stem}")
    print(f"Suffix: {p.suffix}")
    print(f"Parts: {p.parts}")
    print(f"Anchor: {p.anchor}")
    print(…
13 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.