From 736706604d1ade9b267252726944a1cd15d16620 Mon Sep 17 00:00:00 2001 From: Gabriel Gerlero Date: Thu, 22 Aug 2024 22:22:21 -0300 Subject: [PATCH] Add create method to FoamFile --- foamlib/_cases/_base.py | 6 ++---- foamlib/_files/_files.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/foamlib/_cases/_base.py b/foamlib/_cases/_base.py index 4b42fd0..3e01876 100644 --- a/foamlib/_cases/_base.py +++ b/foamlib/_cases/_base.py @@ -62,12 +62,10 @@ def name(self) -> str: return self.path.name def __getitem__(self, key: str) -> FoamFieldFile: - if (self.path / key).is_file(): - return FoamFieldFile(self.path / key) - elif (self.path / f"{key}.gz").is_file(): + if (self.path / f"{key}.gz").is_file() and not (self.path / key).is_file(): return FoamFieldFile(self.path / f"{key}.gz") else: - raise KeyError(key) + return FoamFieldFile(self.path / key) def __contains__(self, obj: object) -> bool: if isinstance(obj, FoamFieldFile): diff --git a/foamlib/_files/_files.py b/foamlib/_files/_files.py index e159745..37ad0eb 100644 --- a/foamlib/_files/_files.py +++ b/foamlib/_files/_files.py @@ -11,6 +11,11 @@ else: from typing import Iterator, Mapping, MutableMapping, Sequence +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + from .._util import is_sequence from ._base import FoamFileBase from ._io import _FoamFileIO @@ -96,6 +101,32 @@ def as_dict(self) -> FoamFileBase._Dict: return ret + def create(self, *, exist_ok: bool = False, parents: bool = False) -> Self: + """ + Create the file. + + Parameters + ---------- + exist_ok : bool, optional + If False (the default), raise a FileExistsError if the file already exists. + If True, do nothing if the file already exists. + parents : bool, optional + If True, also create parent directories as needed. + """ + if self.path.exists(): + if not exist_ok: + raise FileExistsError(self.path) + else: + return self + + if parents: + self.path.parent.mkdir(parents=True, exist_ok=True) + + self.path.touch() + self._write_header() + + return self + @property def version(self) -> float: """Alias of `self["FoamFile", "version"]`.""" @@ -160,6 +191,7 @@ def object_(self, value: str) -> None: def _write_header(self) -> None: assert "FoamFile" not in self + assert not self self["FoamFile"] = {} self.version = 2.0