Extract text in bulk from PDFs in Python: A small batch that runs on an 8GB mini PC
Create a small Python script to extract text from PDFs and save it to CSV. To keep it light on an 8GB mini PC, process one file at a time.
Open a PDF, copy the needed text, paste into Excel. For a few files it's fine, but with dozens you spend half a day. This article introduces a minimal script that extracts text in bulk from PDFs and saves it to CSV.
Good PDFs: Searchable PDFs from Word or Excel. Image scans don't work with this method (OCR is required).
Prep: Virtual environment and pypdf
Use Python 3.12, and make a virtual environment in a project folder. The only extra library is pypdf for reading PDFs.
python -m venv .venv
.venv\Scripts\activate
pip install pypdf
On macOS or Linux, enable the virtual environment with source .venv/bin/activate.
Script that reads PDFs one by one
Put PDFs in the pdfs folder, and save extract_pdf.py in the same place. It processes one file at a time, so an 8GB PC doesn't take much memory.
from pathlib import Path
import csv
from pypdf import PdfReader
BASE = Path(__file__).parent
PDF_DIR = BASE / "pdfs"
OUT = BASE / "pdf_text.csv"
rows = []
for pdf_path in sorted(PDF_DIR.glob("*.pdf")):
try:
reader = PdfReader(str(pdf_path))
texts = []
for page in reader.pages:
texts.append(page.extract_text() or "")
rows.append([pdf_path.name, len(reader.pages), "\n".join(texts)])
print(f"OK: {pdf_path.name}")
except Exception as e:
rows.append([pdf_path.name, 0, f"ERROR: {e}"])
print(f"NG: {pdf_path.name} / {e}")
with OUT.open("w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["file", "pages", "text"])
writer.writerows(rows)
print(f"done: {OUT}")
Running and verifying
- Make the
pdfsfolder and put the target PDFs in it. - Run
python extract_pdf.pyin the terminal. - A
pdf_text.csvis created in the same folder. Opening it in Excel shows the filename, page count, and body.
If text is garbled, specify UTF-8 when opening the CSV in Excel. The code above saves with utf-8-sig, so it opens more easily even with Japanese Excel.
Troubleshooting when it doesn't work
- Body is empty: It's an image PDF, or text isn't embedded. OCR is required.
- Table columns are broken: PDFs don't always preserve table structure. Check if text is extractable first.
- Fails with password-protected PDFs: The
passwordargument ofPdfReaderis needed. Don't process files you don't have permission to. - Memory runs out: Process one file at a time, split large PDFs.
Note: Don't upload PDFs containing company confidential documents or personal information to external Web services. This script runs locally, but follow your company rules for where the output CSV is stored and shared.
Summary
PDF text extraction starts with pypdf and tens of lines of code. Try with around 10 files first, then tidy up the filename rules and output destination when it works. Don't try to automate everything at once — start by reducing copy-paste work.