Search Tutorials
--Ads--Loading PDF, DOCX, HTML, Markdown, CSV and JSON
Python loaders for the most common document formats, with a single unified Document class.
The first step of indexing is getting text out of your files. Real knowledge bases mix PDFs, Word files, web pages, Markdown, spreadsheets and JSON exports. In this lesson you will write a loader for each format and combine them behind one function that returns a common Document object.
A common Document class
Whatever the source format, every later stage needs the same two things: the text, and metadata describing where it came from. A small dataclass keeps the rest of the pipeline independent of file formats.
from dataclasses import dataclass, field
@dataclass
class Document:
text: str
metadata: dict = field(default_factory=dict) # source, page, title, ...
Install the parsing libraries if you have not already:
pip install pypdf python-docx beautifulsoup4 markdown
Plain text and Markdown
from pathlib import Path
def load_text(path: Path) -> list[Document]:
text = path.read_text(encoding="utf-8", errors="replace")
return [Document(text, {"source": str(path), "type": path.suffix.lstrip(".")})]
Keep Markdown as Markdown. Its headings (#, ##) are useful later for structure-aware chunking, and LLMs read Markdown well.
pypdf extracts the text layer of a PDF. Create one Document per page so that you can cite page numbers later.
from pypdf import PdfReader
def load_pdf(path: Path) -> list[Document]:
reader = PdfReader(path)
title = (reader.metadata.title if reader.metadata else None) or path.stem
docs = []
for page_number, page in enumerate(reader.pages, start=1):
text = page.extract_text() or ""
if text.strip():
docs.append(Document(text, {
"source": str(path), "type": "pdf", "page": page_number, "title": title,
}))
return docs
If a PDF page returns no text, it is probably a scanned image. Tables and multi-column pages can also come out scrambled. The next lesson, Parsing Tables, Scanned PDFs and Multi-Column Layouts, deals with these cases.
Word documents (DOCX)
python-docx gives you paragraphs with their style names. Turning heading styles into Markdown headings keeps the document's structure.
import docx
def load_docx(path: Path) -> list[Document]:
d = docx.Document(path)
lines = []
for para in d.paragraphs:
text = para.text.strip()
if not text:
continue
style = para.style.name.lower()
if style.startswith("heading"):
level = int(style.split()[-1]) if style.split()[-1].isdigit() else 1
lines.append("#" * level + " " + text)
else:
lines.append(text)
# Tables are stored separately from paragraphs in DOCX
for table in d.tables:
for row in table.rows:
lines.append(" | ".join(cell.text.strip() for cell in row.cells))
title = d.core_properties.title or path.stem
return [Document("\n\n".join(lines), {"source": str(path), "type": "docx", "title": title})]
HTML pages
Web pages contain a lot of text that is not content: navigation, cookie banners, footers and scripts. Remove those elements before extracting text.
from bs4 import BeautifulSoup
def load_html(path: Path) -> list[Document]:
soup = BeautifulSoup(path.read_text(encoding="utf-8", errors="replace"), "html.parser")
for tag in soup(["script", "style", "nav", "header", "footer", "aside", "form"]):
tag.decompose()
main = soup.find("main") or soup.find("article") or soup.body or soup
title = soup.title.get_text(strip=True) if soup.title else path.stem
text = main.get_text("\n", strip=True)
return [Document(text, {"source": str(path), "type": "html", "title": title})]
CSV files
For CSV data, the right representation depends on the question you expect. When each row is a self-contained record (a product, an FAQ entry, a ticket), turn each row into its own document written as "column: value" lines. The column names give the embedding model the context it needs.
import csv
def load_csv(path: Path) -> list[Document]:
docs = []
with path.open(encoding="utf-8", newline="") as f:
for row_number, row in enumerate(csv.DictReader(f), start=1):
text = "\n".join(f"{key}: {value}" for key, value in row.items() if value)
docs.append(Document(text, {"source": str(path), "type": "csv", "row": row_number}))
return docs
If users will ask aggregate questions ("What was the total revenue in Q3?"), embedding rows is the wrong tool. Use Text-to-SQL instead.
JSON files
JSON exports, such as tickets from a help desk or records from an API, are usually a list of objects. Flatten each object into readable "key: value" lines.
import json
def flatten(obj, prefix=""):
"""Yield 'path: value' lines for every leaf of a nested JSON object."""
if isinstance(obj, dict):
for key, value in obj.items():
yield from flatten(value, f"{prefix}{key}.")
elif isinstance(obj, list):
for i, value in enumerate(obj):
yield from flatten(value, f"{prefix}{i}.")
else:
yield f"{prefix.rstrip('.')}: {obj}"
def load_json(path: Path) -> list[Document]:
data = json.loads(path.read_text(encoding="utf-8"))
records = data if isinstance(data, list) else [data]
return [
Document("\n".join(flatten(record)), {"source": str(path), "type": "json", "record": i})
for i, record in enumerate(records)
]
One function for a whole folder
LOADERS = {
".txt": load_text, ".md": load_text,
".pdf": load_pdf, ".docx": load_docx,
".html": load_html, ".htm": load_html,
".csv": load_csv, ".json": load_json,
}
def load_folder(folder: str) -> list[Document]:
documents = []
for path in sorted(Path(folder).rglob("*")):
loader = LOADERS.get(path.suffix.lower())
if loader is None or not path.is_file():
continue
try:
documents.extend(loader(path))
except Exception as error: # one bad file must not stop the whole run
print(f"Skipped {path}: {error}")
return documents
if __name__ == "__main__":
docs = load_folder("knowledge_base")
print(f"Loaded {len(docs)} documents")
print(docs[0].metadata, docs[0].text[:200])
Log skipped files and empty documents during indexing. Silent failures at this stage are the most common reason a RAG system "doesn't know" something that is in the documents.
Other sources
The same pattern works for any source: write a function that returns Document objects. Common examples are Confluence and Notion (via their APIs), Google Drive, SharePoint, databases, email archives and websites (via a crawler). Frameworks such as LangChain and LlamaIndex ship hundreds of ready-made loaders, covered in Module 13.
Key takeaways
- Normalise every source into a common
Document(text, metadata)object. - Load PDFs per page so answers can cite page numbers.
- Preserve structure: convert headings to Markdown and keep tables.
- Strip navigation and boilerplate from HTML before extracting text.
- Turn records (CSV rows, JSON objects) into "field: value" text; use SQL for aggregate questions.