Money, Rate, CentCount and a bunch of bugfixes.
[python_utils.git] / file_utils.py
index 464b0e76cfba0ef4e80ba5343c24bf433584b9b5..525a1afb0e262e93082f91dc8860a932575ed27a 100644 (file)
@@ -7,11 +7,14 @@ import errno
 import hashlib
 import logging
 import os
+import io
 import pathlib
 import time
 from typing import Optional
 import glob
 from os.path import isfile, join, exists
+from uuid import uuid4
+
 
 logger = logging.getLogger(__name__)
 
@@ -249,3 +252,25 @@ def get_files_recursive(directory: str):
     for subdir in get_directories(directory):
         for file_or_directory in get_files_recursive(subdir):
             yield file_or_directory
+
+
+class FileWriter(object):
+    def __init__(self, filename: str) -> None:
+        self.filename = filename
+        uuid = uuid4()
+        self.tempfile = f'{filename}-{uuid}.tmp'
+        self.handle = None
+
+    def __enter__(self) -> io.TextIOWrapper:
+        assert not does_path_exist(self.tempfile)
+        self.handle = open(self.tempfile, mode="w")
+        return self.handle
+
+    def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
+        if self.handle is not None:
+            self.handle.close()
+            cmd = f'/bin/mv -f {self.tempfile} {self.filename}'
+            ret = os.system(cmd)
+            if (ret >> 8) != 0:
+                raise Exception(f'{cmd} failed, exit value {ret>>8}')
+        return None