Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
Chunk Large File Upload Simulation by Blocks in Python
A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.
import os
import hashlib
from pathlib import Path
def read_file_in_chunks(file_path, chunk_size=8196):
"""Yield chunks of a file as bytes."""
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
yield chunk
def simulate_chunked_upload(file_path, chunk_size=8196):
"""S…
How to Use fcntl for Exclusive File Locking in Python
This code demonstrates how to acquire an exclusive advisory lock on a file using fcntl.flock with a non-blocking flag, simulate work, then release the lock.
import fcntl
import os
import tempfile
import time
def acquire_exclusive_lock(filepath):
fd = os.open(filepath, os.O_RDWR | os.O_CREAT)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
print(f"Exclusive lock acquired on {filepath}")
time.sleep(1) # Simulate work while holding the l…
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.