diff options
author | Helmut Grohne <helmut@subdivi.de> | 2025-06-01 19:46:08 +0200 |
---|---|---|
committer | Helmut Grohne <helmut@subdivi.de> | 2025-06-01 19:46:08 +0200 |
commit | ca32b72b72ce36c2bb987f53056ca2616fcba216 (patch) | |
tree | 458e363471ab4f1fbf9534cd13a9e3a0eb6148c8 | |
parent | 82e056900471621799037d3e1df30d796236c9a3 (diff) | |
download | python-linuxnamespaces-ca32b72b72ce36c2bb987f53056ca2616fcba216.tar.gz |
New methods AtLocation.write_{bytes,text}
They bring similarity to their pathlib.Path counterparts.
-rw-r--r-- | linuxnamespaces/atlocation.py | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/linuxnamespaces/atlocation.py b/linuxnamespaces/atlocation.py index d30e88f..0e2be87 100644 --- a/linuxnamespaces/atlocation.py +++ b/linuxnamespaces/atlocation.py @@ -9,6 +9,7 @@ code for doing so. import enum import errno +import locale import os import os.path import pathlib @@ -551,6 +552,26 @@ class AtLocation: AtLocation(dirfd), ) + def write_bytes(self, data: bytes) -> None: + """Overwrite the file with the given data bytes.""" + dataview = memoryview(data) + with self.open(os.O_CREAT | os.O_WRONLY) as fd: + while dataview: + written = os.write(fd, dataview) + dataview = dataview[written:] + + def write_text( + self, data: str, encoding: str | None = None, errors: str | None = None + ) -> None: + """Overwrite the file with the given data string.""" + if encoding is None: + encoding = locale.getencoding() + if errors is None: + databytes = data.encode(encoding=encoding) + else: + databytes = data.encode(encoding=encoding, errors=errors) + self.write_bytes(databytes) + def __enter__(self) -> "AtLocation": """When used as a context manager, the associated fd will be closed on scope exit. |