Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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 Read a File with Retry on Temporary IOError in Python
Read a file with automatic retries on temporary IOError/OSError failures, using the pathlib module with configurable attempts and delay.
import time
from pathlib import Path
def read_file_with_retry(filepath: str | Path, max_attempts: int = 3, delay: float = 0.5) -> str:
"""Read a file with retries on temporary IO errors."""
path = Path(filepath)
last_error = None
for attempt in range(max_attempts):
try:
return pat…
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.