Source code for Muscat.Helpers.IO.FileTools

# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#
from typing import Tuple, Union
import tempfile

from Muscat.Helpers.IO.TemporaryDirectory import TemporaryDirectory


[docs] def WriteTempFile(filename: str, content: Union[str, bytes], mode: str = "w") -> str: """Create and fill a temporary file on the temporary folder read the documentation of TemporaryDirectory Parameters ---------- filename : str the name of the file to be created content : str, optional the content of the file, by default None mode : str, optional read python "open" function documentation for more detail, by default "w" Returns ------- str the name of the filename (with the path attached) Raises ------ Exception if error during the file creation """ pFile = TemporaryDirectory.GetTempPath() + filename with open(pFile, mode) as f: f.write(content) return pFile raise Exception(f"Unable ot create file :{pFile}") # pragma no coverage
[docs] def GetUniqueTempFile(suffix: str = "", prefix: str = 'tmp') -> Tuple[int, str]: """Create a unique temporary file on the temp directory Parameters ---------- suffix : str, optional If 'suffix' is not None, the file name will end with that suffix, otherwise there will be no suffix., by default "" prefix : str, optional If 'prefix' is not None, the file name will begin with that prefix, otherwise a default prefix is used., by default 'tmp' Returns ------- Tuple[int,str] please read the doc of module tempfile.mkstemp """ (fd, filename) = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=TemporaryDirectory.GetTempPath()) return (fd, filename)
[docs] def CheckIntegrity(GUI: bool = False): print(f"{GetUniqueTempFile('.ext')=}") WriteTempFile("testFile", content="hello World") return "OK"