Write File

Writes the provided content (text or bytes) to the specified file location.

Write File


Processing

This function writes the provided content, which can be either text or binary data, to a specified file location.

Inputs

file_path
The full file path where it will be written.
content
The data (text or bytes) to write to the file.

Inputs Types

Input Types
file_path Str, FilePath
content Str, Bytes

You can check the list of supported types here: Available Type Hints.

Outputs

full path
The absolute path of the created file.
status
A boolean indicating whether the file was successfully written.

Outputs Types

Output Types
full path Str, None
status Bool

You can check the list of supported types here: Available Type Hints.

Options

The Write File brick contains some changeable options:

Overwrite
Determines whether an existing file at the specified path can be overwritten. Defaults to True.
Silent Mode
If enabled, suppresses raising exceptions for errors, returning a failure status instead. Defaults to True.
Verbose
Controls whether detailed logging messages are generated during execution. Defaults to True.
import logging
from coded_flows.types import Str, FilePath, Tuple, Bytes, Union, Bool

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def write_file(
    file_path: Union[Str, FilePath], content: Union[Str, Bytes], options
) -> Tuple[Str, Bool]:
    brick_display_name = "Write File"
    options = options or {}
    verbose = options.get("verbose", True)
    overwrite = options.get("overwrite", True)
    silent_mode = options.get("silent_mode", True)
    path = FilePath(file_path)
    full_path = str(path.resolve())
    status = True
    if path.exists() and path.is_dir():
        verbose and logger.error(
            f"[{brick_display_name}] Path '{path}' points to an existing directory, not a file."
        )
        status = False
        if not silent_mode:
            raise ValueError(
                f"Path '{path}' points to an existing directory, not a file."
            )
    if path.exists() and (not overwrite):
        verbose and logger.error(
            f"[{brick_display_name}] File '{path}' already exists."
        )
        status = False
        if not silent_mode:
            raise FileExistsError(f"File '{path}' already exists.")
    try:
        path.parent.mkdir(parents=True, exist_ok=True)
        if isinstance(content, bytes):
            mode = "wb"
        else:
            mode = "w"
            content = str(content)
        verbose and logger.info(
            f"[{brick_display_name}] Received a {('textual' if mode == 'w' else 'binary')} input."
        )
        with path.open(mode, encoding="utf-8" if mode == "w" else None) as f:
            f.write(content)
    except PermissionError as e:
        status = False
        verbose and logger.error(
            f"[{brick_display_name}] Cannot access path '{path}': Permission denied."
        )
        if not silent_mode:
            raise PermissionError(
                f"Cannot access path '{path}': Permission denied"
            ) from e
    except OSError as e:
        status = False
        verbose and logger.error(
            f"[{brick_display_name}] Failed to process path '{path}'."
        )
        if not silent_mode:
            raise OSError(f"Failed to process path '{path}': {str(e)}") from e
    except Exception as e:
        status = False
        verbose and logger.error(
            f"[{brick_display_name}] Failed to create file '{path}'."
        )
        if not silent_mode:
            raise OSError(f"Failed to create file '{path}': {str(e)}") from e
    logger.info(
        f"[{brick_display_name}] Path '{full_path}' {('created successfully' if status else 'could not be created')}."
    )
    return (full_path, status)

Brick Info

version v0.1.4
python 3.10, 3.11, 3.12, 3.13
requirements
    -