← 中文资源

简体中文版本

带回滚的原子文件替换

先在目标目录创建临时文件,写入并 fsync 后使用 os.replace 原子替换目标,失败时清理临时文件并重新抛出异常。

阅读英文原文

题目

实现 atomic_write(path, data),把文本以 UTF-8 写入目标文件。流程是:在目标文件所在目录创建临时文件,写入内容,flush 后调用 os.fsync 确保数据落盘,再用 os.replace 原子替换目标。任何一步失败都必须删除临时文件,并原样抛出异常。函数返回写入的 UTF-8 字节数,而不是字符数。

  • 输入:目标路径和文本内容。
  • 输出:实际写入的 UTF-8 字节数;目标文件内容与输入完全一致,目录中不残留临时文件。

解题思路

临时文件必须与目标位于同一文件系统,因为 os.replace 只在该前提下保证原子性。tempfile.mkstemp 返回文件描述符和唯一路径,os.fdopen 包装描述符,with 退出时自动关闭。flush 把 Python 缓冲区数据交给操作系统,fsync 再把数据刷到磁盘,之后执行重命名,读者只会看到完整的旧文件或完整的新文件。

异常处理使用 except BaseException,覆盖普通异常、KeyboardInterrupt 等情况。清理时尝试 unlink 临时文件,文件已不存在则忽略 FileNotFoundError,最后用裸 raise 保留原始异常和堆栈。返回值通过 data.encode(“utf-8”) 计算,因此非 ASCII 字符会占多个字节。

参考实现要点

  1. 校验 data 是字符串,计算目标绝对路径所在目录并确保存在。
  2. 用 mkstemp 在目标目录创建带唯一名称的临时文件。
  3. 用 os.fdopen 以 UTF-8 打开描述符,写入后 flush 并 os.fsync。
  4. 关闭临时文件后调用 os.replace(tmp_path, path) 完成原子替换。
  5. 异常时删除临时文件并重新抛出;成功后返回 UTF-8 字节长度。

常见错误

  • 把临时文件放在系统临时目录,跨文件系统时 os.replace 可能失败或失去原子性。
  • 只 flush 不 fsync,断电后新文件可能为空或不完整。
  • 捕获异常后返回 False 而不重新抛出,调用方误以为写入成功。
  • 用 len(data) 作为字节数,遇到中文、é 或 emoji 时结果偏小。

验证方式

写入 hello 应返回 5,写入 café 也应返回 5,因为 é 在 UTF-8 中占两个字节。再测试嵌套目录、覆盖已有文件、空字符串和含 emoji 的内容。通过只读目录或非字符串参数制造失败,确认异常类型未被改变,且目录中没有 .part 残留。最后重新读取目标文件,与原始内容逐字节比较。

代码示例

import os
import tempfile


def atomic_write(path, data):
    if not isinstance(data, str):
        raise TypeError("data must be a string")
    directory = os.path.dirname(os.path.abspath(path))
    os.makedirs(directory, exist_ok=True)
    fd, tmp_path = tempfile.mkstemp(prefix=".tmp-", suffix=".part", dir=directory)
    try:
        with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
            handle.write(data)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp_path, path)
    except BaseException:
        try:
            os.unlink(tmp_path)
        except FileNotFoundError:
            pass
        raise
    return len(data.encode("utf-8"))


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as directory:
        target = os.path.join(directory, "out.txt")
        print(atomic_write(target, "hello"))
        with open(target, encoding="utf-8") as handle:
            print(handle.read())