elastic-recheck/elastic_recheck/utils.py
Sorin Sbarnea 5104f277b8 Make file writing atomic
This should render the need to use wrappers obsolete as all
file writing operations are now atomic, assuring that we either
write the entire file or fail.

That is important as we do not want to end-up serving partial files
with the web-server.

Change-Id: I696e2474b557e6b5fea707a198f32cea721cc150
2020-11-09 10:02:18 +00:00

17 lines
397 B
Python

import os
import sys
from typing import Optional
def atomic_write(filename: Optional[str], data: str) -> None:
"""Atomically writes a file.
If filename is not mentioned, it will write to sys.stdout
"""
if filename:
with open(f"{filename}.tmp", "w") as f:
f.write(data)
os.replace(f"{filename}.tmp", filename)
else:
sys.stdout.write(data)