"""Standard-library CSV loader."""
import csv
from langchain_core.documents import Document
from .base import BaseFileLoader
[docs]
class CSVFileLoader(BaseFileLoader):
"""Load CSV rows as individual LangChain documents."""
[docs]
def load(self) -> list[Document]:
"""Parse rows while retaining source and row-number metadata."""
encoding = self.kwargs.get("encoding", "utf-8")
try:
with self.file_path.open(encoding=encoding, newline="") as file:
reader = csv.DictReader(file)
return [
Document(
page_content="\n".join(
f"{key}: {value or ''}" for key, value in row.items()
),
metadata={"source": str(self.file_path), "row": row_number},
)
for row_number, row in enumerate(reader, start=1)
]
except (OSError, UnicodeError, csv.Error) as exc:
raise RuntimeError(
f"Failed to load CSV file {self.file_path}: {exc}"
) from exc
[docs]
@staticmethod
def get_install_command() -> str:
"""Return the installation command for this built-in loader."""
return "No additional dependencies required."