Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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 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:
…
Export List of Dicts to CSV in Python
Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.
import csv
def export_to_csv(data, filename):
"""Export a list of dicts to a CSV file."""
if not data:
print("No data to export")
return
# Get column names from the keys of the first dict
fieldnames = list(data[0].keys())
with open(filename, 'w', newline='', encoding='utf…
File Data Helper Functions in Python
Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.
from pathlib import Path
def load_text_file(filepath):
"""Read a text file and return its contents as a string."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
return path.read_text(encoding="utf-8")
def save_text_file(filepath, content):
…
How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python
Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.
import csv
from pathlib import Path
def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
if not rows_a or not rows_b:
return []
columns = list(rows_a[0].key…
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.
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…
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.
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…
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.
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()…
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.
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…
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.
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
…
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.
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"…
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.
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__"…
How to Sort Files by Name and Size in Python
Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.
from pathlib import Path
def sort_files_data(files):
"""Sort a list of file dictionaries by name, then by size."""
return sorted(files, key=lambda f: (f["name"], f["size"]))
if __name__ == "__main__":
files_data = [
{"name": "report.pdf", "size": 2048},
{"name": "data.csv", "size": 1024},…
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.
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…
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.
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…
Parse CSV with Custom Delimiter and Quote Character in Python
Reads a CSV string with a custom delimiter and quote character using the csv module, returning a list of rows.
import csv
from io import StringIO
def parse_csv(data, delimiter='|', quotechar='"'):
reader = csv.reader(StringIO(data), delimiter=delimiter, quotechar=quotechar)
rows = [row for row in reader]
return rows
if __name__ == "__main__":
sample = 'Alice|"Smith, Jr."|25\nBob|"Johnson, Sr."|30'
result …
Read Parquet-Like Columnar CSV Chunks in Python
A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.
```python
import csv
from pathlib import Path
from typing import Iterator, List
def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
"""Read CSV data in columnar chunks, similar to how parquet stores columns."""
csv_file = Path(csv_path)
with csv_f…
Read a CSV File with csv.DictReader in Python
Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.
import csv
from pathlib import Path
def read_csv_with_dictreader(file_path):
data = []
with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
if __name__ == "__main__":
# Cre…
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.
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:…
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.