Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

2 matches
Files & data medium

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.

fcntl file-locking flock
Python
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…
12 0 Open
Algorithms & data structures easy

Simplify a File Path in Python with a Stack

Uses a stack to normalize an absolute Unix path by handling '.', '..', and duplicate slashes.

stack string path
Python
from pathlib import PurePosixPath

def simplify_path(path: str) -> str:
    tokens = path.split('/')
    stack = []
    
    for token in tokens:
        if not token or token == '.':
            continue
        if token == '..':
            if stack:
                stack.pop()
        else:
            stack.append…
11 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.