Python 原子替换文本文件:同目录临时文件、失败清理与 fsync 边界

10-21 5阅读

脚本更新配置、生成索引或保存小型状态文件时,直接以写入模式打开旧文件,会先截断旧内容。如果后续编码或写入失败,读者可能拿到空文件。本文实现一个更稳妥的流程:在目标目录写好临时文件,关闭句柄,再用 os.replace 切换目标名称;同时明确它没有提供哪些保证。

Python 原子替换文本文件:同目录临时文件、失败清理与 fsync 边界
AI 生成的概念示意图:新文件准备完成后替换旧文件的路径指向,并非真实系统截图,也不是精确的 inode 结构图。

先分清名称原子性与断电持久性

在支持相应语义的文件系统上,一次成功的替换不会把目标名称暴露为“只写了一半的新文件”。原子性针对名称切换,不代表整个业务事务成功,更不代表突然断电后必然保留新版本。Python 文档说明,成功的重命名操作具有原子性要求,跨文件系统则可能失败,所以临时文件必须放在目标的同一目录。参见 os.replace 官方说明。

本例的 sync_file=True 仅在替换前对临时文件执行 flush 和 fsync。它不对替换后的父目录做同步,不能称为完整的断电持久化方案。Linux 手册明确指出,文件 fsync 不必然同步目录项;目录还需要单独同步。其他平台及存储设备必须另行验证。参见 Python fsync 说明及 Linux fsync 手册。

实现只处理可信目录内的小文本

接口接收字符串路径或返回字符串的 PathLike,以及字符串正文。它先完成 UTF-8 编码,再创建临时文件,避免编码异常影响旧内容。二进制写入保留正文已有换行,不自动插入 BOM,也不把换行改成平台默认形式;全文会驻留内存,因此不适合大文件。

父目录必须已经存在。路径不能包含 .. 父级跳转组件,以免路径规范化与符号链接组合后指向意外位置。实现拒绝目录和目标符号链接,但这些预检查不能防御检查后路径被恶意替换的竞态。请只用于自己控制、结构稳定的目录;它不是任意路径的安全沙箱。mkstemp 创建独立临时文件后,代码负责关闭描述符并清理残留,依据 tempfile 官方说明。

implementation.py 完整代码

"""Replace a small UTF-8 file in a trusted, stable directory."""
import os
from pathlib import Path
import tempfile


def replace_text(path, text, *, sync_file=False):
    """Replace the name atomically; do not promise crash durability."""
    if not isinstance(text, str):
        raise TypeError('text must be str')
    if not isinstance(sync_file, bool):
        raise TypeError('sync_file must be bool')
    raw = os.fspath(path)
    if not isinstance(raw, str):
        raise TypeError('path must be a text path')
    if not raw or '\0' in raw:
        raise ValueError('path must be nonempty and contain no NUL')
    if '..' in Path(raw).parts:
        raise ValueError('parent traversal is not supported')
    target = Path(os.path.abspath(raw))
    if target.is_symlink():
        raise ValueError('symbolic-link targets are not supported')
    if target.exists() and not target.is_file():
        raise ValueError('target must be a regular file or absent')
    data = text.encode('utf-8')
    fd, name = tempfile.mkstemp(
        prefix='.atomic-', suffix='.tmp', dir=target.parent
    )
    temporary = Path(name)
    try:
        try:
            stream = os.fdopen(fd, 'wb')
        except BaseException:
            os.close(fd)
            raise
        with stream:
            if stream.write(data) != len(data):
                raise OSError('short write')
            stream.flush()
            if sync_file:
                os.fsync(stream.fileno())
        os.replace(temporary, target)
    finally:
        try:
            temporary.unlink()
        except FileNotFoundError:
            pass

清理策略与失败边界

编码、写入、flush、文件 fsync 或关闭句柄出错时,替换尚未执行;在没有其他写入者干扰的前提下,旧内容仍在。替换调用失败时,下面的故障注入测试同样验证旧内容和临时文件清理。不要把模拟异常等同于断电、内核崩溃或真实磁盘故障测试。

finally 只删除本次创建的临时路径,不扫描目录清理其他文件。若进程被强制结束,清理代码可能根本没机会运行;若删除被拒绝,异常会继续暴露,临时文件也可能残留。因此生产日志应记录错误,不能把“通常能清理”写成“绝无残留”。不要为隐藏异常而自动放宽目录权限。

完整测试与可复现实验

将两个文件放在同一目录,执行 python -m unittest -v test_implementation.py。每个测试自行创建 TemporaryDirectory,所有测试数据只写在该临时目录内,不读取或修改用户配置。失败路径通过 mock 注入,不依赖磁盘写满或竞争时序。

下面共二十二项测试,覆盖新建、覆盖、中文和表情、空正文、换行、同目录顺序、无残留、短写、写入及替换异常、描述符关闭、非法参数和同步分支。真实文件 fsync 测试遇到明确的不支持错误才跳过;其他错误仍判失败。模拟顺序测试还检查同步前数据已离开 Python 缓冲。

test_implementation.py 完整代码

import errno
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

import implementation as app


class AtomicTextTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.target = self.root / 'config.txt'
        self.target.write_text('old', encoding='utf-8')

    def assert_old_and_clean(self):
        self.assertEqual(self.target.read_bytes(), b'old')
        self.assertEqual(set(self.root.iterdir()), {self.target})

    def test_existing_file(self):
        app.replace_text(self.target, 'new')
        self.assertEqual(self.target.read_bytes(), b'new')

    def test_new_file(self):
        target = self.root / 'new.txt'
        app.replace_text(target, 'created')
        self.assertEqual(target.read_bytes(), b'created')

    def test_unicode(self):
        text = '云鹊\nemoji: 🐦\n'
        app.replace_text(self.target, text)
        self.assertEqual(self.target.read_bytes(), text.encode('utf-8'))

    def test_empty_content(self):
        app.replace_text(self.target, '')
        self.assertEqual(self.target.read_bytes(), b'')

    def test_newlines_unchanged(self):
        app.replace_text(self.target, 'a\r\nb\nc\r')
        self.assertEqual(self.target.read_bytes(), b'a\r\nb\nc\r')

    def test_no_temporary_left_after_success(self):
        app.replace_text(str(self.target), 'new')
        self.assertEqual(set(self.root.iterdir()), {self.target})

    def test_same_directory_and_complete_before_replace(self):
        real_replace = os.replace

        def observe(src, dst):
            self.assertEqual(Path(src).parent, self.root)
            self.assertEqual(Path(src).read_bytes(), b'new')
            self.assertEqual(Path(dst).read_bytes(), b'old')
            real_replace(src, dst)

        with patch.object(app.os, 'replace', side_effect=observe):
            app.replace_text(self.target, 'new')
        self.assertEqual(self.target.read_bytes(), b'new')

    def test_write_failure_cleans_up_and_preserves_old(self):
        real_fdopen = os.fdopen

        def broken_open(fd, mode):
            stream = real_fdopen(fd, mode)
            def fail(data):
                raise OSError('injected write failure')

            stream.write = fail
            return stream

        with patch.object(app.os, 'fdopen', side_effect=broken_open):
            with self.assertRaises(OSError):
                app.replace_text(self.target, 'new')
        self.assert_old_and_clean()

    def test_short_write_preserves_old(self):
        real_fdopen = os.fdopen

        def short_open(fd, mode):
            stream = real_fdopen(fd, mode)
            stream.write = lambda data: 0
            return stream

        with patch.object(app.os, 'fdopen', side_effect=short_open):
            with self.assertRaisesRegex(OSError, 'short write'):
                app.replace_text(self.target, 'new')
        self.assert_old_and_clean()

    def test_replace_failure_cleans_up_and_preserves_old(self):
        with patch.object(app.os, 'replace', side_effect=OSError('injected')):
            with self.assertRaises(OSError):
                app.replace_text(self.target, 'new')
        self.assert_old_and_clean()

    def test_fdopen_failure_closes_descriptor(self):
        real_close = os.close
        with patch.object(app.os, 'close', wraps=real_close) as close:
            with patch.object(app.os, 'fdopen', side_effect=OSError('injected')):
                with self.assertRaises(OSError):
                    app.replace_text(self.target, 'new')
            close.assert_called_once()
        self.assert_old_and_clean()

    def test_encoding_failure_preserves_old(self):
        with self.assertRaises(UnicodeEncodeError):
            app.replace_text(self.target, '\ud800')
        self.assert_old_and_clean()

    def test_invalid_text(self):
        with self.assertRaises(TypeError):
            app.replace_text(self.target, b'not text')
        self.assert_old_and_clean()

    def test_invalid_sync_flag(self):
        with self.assertRaises(TypeError):
            app.replace_text(self.target, 'new', sync_file=1)
        self.assert_old_and_clean()

    def test_invalid_path(self):
        for path in (None, 123, bytes(self.target)):
            with self.subTest(path=path), self.assertRaises(TypeError):
                app.replace_text(path, 'new')
        for path in ('', str(self.root / 'bad\0name')):
            with self.subTest(path=path), self.assertRaises(ValueError):
                app.replace_text(path, 'new')
        self.assert_old_and_clean()

    def test_parent_traversal_rejected(self):
        target = self.root / 'unused' / '..' / 'config.txt'
        with self.assertRaises(ValueError):
            app.replace_text(target, 'new')
        self.assert_old_and_clean()

    def test_directory_rejected(self):
        with self.assertRaises(ValueError):
            app.replace_text(self.root, 'new')
        self.assert_old_and_clean()

    def test_missing_parent(self):
        with self.assertRaises(FileNotFoundError):
            app.replace_text(self.root / 'missing' / 'x.txt', 'new')
        self.assert_old_and_clean()

    def test_sync_disabled(self):
        with patch.object(app.os, 'fsync') as sync:
            app.replace_text(self.target, 'new')
            sync.assert_not_called()

    def test_sync_before_replace_and_after_flush(self):
        events = []
        real_replace = os.replace

        def sync(fd):
            temporary = next(self.root.glob('.atomic-*.tmp'))
            self.assertEqual(temporary.read_bytes(), b'new')
            events.append('sync')

        def replace(src, dst):
            events.append('replace')
            real_replace(src, dst)

        with patch.object(app.os, 'fsync', side_effect=sync):
            with patch.object(app.os, 'replace', side_effect=replace):
                app.replace_text(self.target, 'new', sync_file=True)
        self.assertEqual(events, ['sync', 'replace'])

    def test_sync_failure_preserves_old(self):
        with patch.object(app.os, 'fsync', side_effect=OSError('injected')):
            with self.assertRaises(OSError):
                app.replace_text(self.target, 'new', sync_file=True)
        self.assert_old_and_clean()

    def test_real_sync_if_supported(self):
        try:
            app.replace_text(self.target, 'synced', sync_file=True)
        except OSError as error:
            unsupported = {errno.EINVAL, errno.ENOSYS, errno.ENOTSUP}
            if error.errno in unsupported:
                self.assert_old_and_clean()
                self.skipTest('file fsync unsupported on this filesystem')
            raise
        self.assertEqual(self.target.read_bytes(), b'synced')
        self.assertEqual(set(self.root.iterdir()), {self.target})


if __name__ == '__main__':
    unittest.main()

上线前还要回答的两个问题

第一,新文件能否沿用旧文件的权限与所有者?不能默认如此。替换后目标对应临时文件,旧文件的权限、所有者、ACL 等元数据不会被本例自动复制;临时文件的默认权限还可能比旧文件更严格。需要保留元数据时,应单独设计并验证策略,不能随手增加 chmod 或 chown 来“修好”访问问题。

第二,多进程能否同时安全更新?本例没有锁,也没有版本比较。两个写入者即使各自完成原子替换,后一次仍可能覆盖前一次;“读取、修改、写回”尤其会丢更新。需要协调时,应采用经过设计的锁或事务存储,而不是把 os.replace 当成并发控制。

实测环境为 Linux 6.18.55 x86_64、CPython 3.12.14,二十二项全部通过,无跳过。未测试 Windows、macOS、网络文件系统或断电恢复;Windows 的共享句柄和权限限制也可能让替换失败。本文核验日期为北京时间 2026 年 10 月 21 日,文档版本与本机补丁版本不必完全一致,测试结论只覆盖上述环境。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。