python
49 lines · 8 steps
Transactional file operations in Python
A FileTransaction records an undo action for every filesystem change so a failure can roll everything back.
Explained by
highlit
1import os
2import shutil
3import tempfile
4from contextlib import contextmanager
5
6
7class FileTransaction:
8 def __init__(self):
9 self._undo = []
10
11 def write(self, path, data):
12 existed = os.path.exists(path)
13 backup = None
14 if existed:
15 fd, backup = tempfile.mkstemp()
16 os.close(fd)
17 shutil.copy2(path, backup)
18 mode = "wb" if isinstance(data, (bytes, bytearray)) else "w"
19 with open(path, mode) as f:
20 f.write(data)
21 if existed:
22 self._undo.append(lambda: shutil.move(backup, path))
23 else:
24 self._undo.append(lambda: os.remove(path))
25
26 def move(self, src, dst):
27 shutil.move(src, dst)
28 self._undo.append(lambda: shutil.move(dst, src))
29
30 def remove(self, path):
31 fd, backup = tempfile.mkstemp()
32 os.close(fd)
33 shutil.move(path, backup)
34 self._undo.append(lambda: shutil.move(backup, path))
35
36 def rollback(self):
37 for action in reversed(self._undo):
38 action()
39 self._undo.clear()
40
41
42@contextmanager
43def file_transaction():
44 tx = FileTransaction()
45 try:
46 yield tx
47 except Exception:
48 tx.rollback()
49 raise
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recording an inverse action per operation lets you undo a sequence of side effects atomically.
- 2Backing up originals to temp files before overwriting makes writes and deletes reversible.
- 3Replaying undo actions in reverse order correctly unwinds dependent changes.
Related explainers
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/transactional-file-operations-in-python-explained-python-faa6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.