"""Standard backend for local files on a hard drive.This backends loads data from and saves data to the local hard drive."""importosfromtypingimportLiteralfrom.baseimportDataBackend
[docs]classFileBackend(DataBackend):"""Raw file from hard disk data backend."""
[docs]defisfile(self,filepath:str)->bool:"""Check if filepath is a file. Args: filepath (str): Path to file. Returns: bool: True if file exists, False otherwise. """returnos.path.isfile(filepath)
[docs]deflistdir(self,filepath:str)->list[str]:"""List all files in the directory. Args: filepath (str): Path to file. Returns: list[str]: List of all files in the directory. """returnsorted(os.listdir(filepath))
[docs]defexists(self,filepath:str)->bool:"""Check if filepath exists. Args: filepath (str): Path to file. Returns: bool: True if file exists, False otherwise. """returnos.path.exists(filepath)
[docs]defset(self,filepath:str,content:bytes,mode:Literal["w","a"]="w")->None:"""Write the file content to disk. Args: filepath (str): Path to file. content (bytes): Content to write in bytes. mode (Literal["w", "a"], optional): Overwrite or append mode. Defaults to "w". """os.makedirs(os.path.dirname(filepath),exist_ok=True)mode_binary:Literal["wb","ab"]="wb"ifmode=="w"else"ab"withopen(filepath,mode_binary)asf:f.write(content)
[docs]defget(self,filepath:str)->bytes:"""Get file content as bytes. Args: filepath (str): Path to file. Raises: FileNotFoundError: If filepath does not exist. Returns: bytes: File content as bytes. """ifnotself.exists(filepath):raiseFileNotFoundError(f"File not found:"f" {filepath}")withopen(filepath,"rb")asf:value_buf=f.read()returnvalue_buf
[docs]defclose(self)->None:"""No need to close manually."""