Esempio n. 1
0
 def write_file(
     self,
     path: PATH_TYPES,
     contents: str | bytes,
     encoding: str | None = None,
 ) -> None:
     if not isinstance(path, self.PATH_BACKEND):
         path = self.PATH_BACKEND(path)
     if isinstance(contents, str):
         with path.open(mode="w", encoding=encoding) as fp:
             fp.write(contents)
     elif isinstance(contents, bytes):
         with path.open(mode="wb") as fp:
             fp.write(contents)
     return
Esempio n. 2
0
 def rewrite(
     self, filepath: PATH_TYPES, mode: str = "w", **kw: Any
 ) -> Generator[IO, None, None]:
     """Rewrite an existing file atomically to avoid programs running in
     parallel to have race conditions while reading."""
     if not isinstance(filepath, self.PATH_BACKEND):
         filepath = self.PATH_BACKEND(filepath)
     with filepath.open(mode=mode, **kw) as fh:
         yield fh
Esempio n. 3
0
 def open_file(
     self, path: PATH_TYPES, text: bool = True, encoding: str = "utf-8"
 ) -> Generator[IO, None, None]:
     if not isinstance(path, self.PATH_BACKEND):
         path = self.PATH_BACKEND(path)
     mode = "r" if text else "rb"
     file_encoding = None
     if text:
         file_encoding = encoding
     with path.open(mode=mode, encoding=file_encoding) as fh:
         yield fh
Esempio n. 4
0
 def open_file(  # noqa
         self,
         path: PATH_TYPES,
         text: bool = True,
         encoding: str = "utf-8") -> Generator[IO, None, None]:
     """Yield a file context to iterate over. If text is true, open the file with
     'rb' mode specified."""
     mode = "r" if text else "rb"
     file_encoding = None
     if text:
         file_encoding = encoding
     if not isinstance(path, pathlib.Path):
         path = pathlib.Path(path)
     with path.open(mode=mode, encoding=file_encoding) as fh:
         yield fh