# -*- coding: utf-8 -*-""" Operators for txt file and directory. """importosfromagentscope.service.service_responseimportServiceResponsefromagentscope.service.service_statusimportServiceExecStatus
[docs]defread_text_file(file_path:str)->ServiceResponse:""" Read the content of the text file. Args: file_path (`str`): The path to the text file to be read. Returns: `ServiceResponse`: A tuple (bool, str) where the boolean indicates success, and the str contains the file content or an error message if any, including the error type. """try:withopen(file_path,"r",encoding="utf-8")asfile:returnServiceResponse(status=ServiceExecStatus.SUCCESS,content=file.read(),)exceptExceptionase:error_message=f"{e.__class__.__name__}: {e}"returnServiceResponse(status=ServiceExecStatus.ERROR,content=error_message,)
[docs]defwrite_text_file(file_path:str,content:str,overwrite:bool=False,)->ServiceResponse:""" Write content to a text file. Args: file_path (`str`): The path to the file where content will be written. content (`str`): Content to write into the file. overwrite (`bool`, defaults to `False`): Whether to overwrite the file if it already exists. Returns: `ServiceResponse`: where the boolean indicates success, and the str contains an error message if any, including the error type. """ifnotoverwriteandos.path.exists(file_path):returnServiceResponse(status=ServiceExecStatus.ERROR,content="FileExistsError: The file already exists.",)try:withopen(file_path,"w",encoding="utf-8")asfile:file.write(content)returnServiceResponse(status=ServiceExecStatus.SUCCESS,content="Success",)exceptExceptionase:error_message=f"{e.__class__.__name__}: {e}"returnServiceResponse(status=ServiceExecStatus.ERROR,content=error_message,)