[docs]classTextLoader(BaseLoader):"""Load text file. Args: file_path: Path to the file to load. encoding: File encoding to use. If `None`, the file will be loaded with the default system encoding. autodetect_encoding: Whether to try to autodetect the file encoding if the specified encoding fails. """
[docs]def__init__(self,file_path:Union[str,Path],encoding:Optional[str]=None,autodetect_encoding:bool=False,):"""Initialize with file path."""self.file_path=file_pathself.encoding=encodingself.autodetect_encoding=autodetect_encoding
[docs]deflazy_load(self)->Iterator[Document]:"""Load from file path."""text=""try:withopen(self.file_path,encoding=self.encoding)asf:text=f.read()exceptUnicodeDecodeErrorase:ifself.autodetect_encoding:detected_encodings=detect_file_encodings(self.file_path)forencodingindetected_encodings:logger.debug(f"Trying encoding: {encoding.encoding}")try:withopen(self.file_path,encoding=encoding.encoding)asf:text=f.read()breakexceptUnicodeDecodeError:continueelse:raiseRuntimeError(f"Error loading {self.file_path}")fromeexceptExceptionase:raiseRuntimeError(f"Error loading {self.file_path}")fromemetadata={"source":str(self.file_path)}yieldDocument(page_content=text,metadata=metadata)