Welcome To Datagrunt

Datagrunt is a Python library designed to simplify the way you work with CSV, Excel, Parquet, and PDF files. It provides a streamlined approach to reading, processing, and transforming your data into various formats, making data manipulation efficient and intuitive.
Why Datagrunt?
Born out of real-world frustration, Datagrunt eliminates the need for repetitive coding when handling CSV, Excel, Parquet, and PDF files. Whether you're a data analyst, data engineer, or data scientist, Datagrunt empowers you to focus on insights, not tedious data wrangling.
What Datagrunt Is Not
Datagrunt is not an extension of or a replacement for DuckDB, Polars, or PyArrow, nor is it a comprehensive data processing solution. Instead, it's designed to simplify the way you work with CSV, Excel, Parquet, and PDF files — solving the pain point of inferring delimiters when a CSV structure is unknown, reading Excel workbooks sheet by sheet, reading and converting columnar Parquet data, and turning PDFs into structured, queryable data. Datagrunt provides an easy way to convert CSV, Excel, and Parquet files to dataframes and export them to various formats, and to extract text, tables, and images from PDFs. One of Datagrunt's value propositions is its relative simplicity and ease of use.
Key Features
- Intelligent Delimiter Inference: Datagrunt automatically detects and applies the correct delimiter for your CSV files.
- Rust-Accelerated Core (v4.0+): CSV delimiter and dialect inference run in a bundled Rust extension (
datagrunt._native) for multiple-times-faster scanning of large files. The native engine is the default and is required on supported platforms (it ships as a prebuilt wheel). A byte-for-byte-equivalent pure-Python implementation lives alongside it as the differential-parity oracle — validated against the Rust engine in CI and selectable via a hidden diagnostics toggle — so results are identical no matter which path runs.
- Path Object Support: Full support for both string paths and
pathlib.Path objects for modern, cross-platform file handling.
- Multiple Processing Engines: Choose from three powerful engines - DuckDB, Polars, and PyArrow - to handle your data processing needs.
- Flexible Data Transformation: Easily convert your processed CSV, Excel, and Parquet data into various formats including CSV, Excel, JSON, JSONL, and Parquet.
- Excel Reading & Writing: Read
.xlsx/.xls workbooks sheet by sheet into DataFrames, dicts, Arrow, or SQL, and export any sheet (or all of them) to CSV, JSON, JSONL, Parquet, or Excel.
- Parquet Reading & Writing: Read
.parquet files into DataFrames, dicts, Arrow tables, or SQL, and export to CSV, JSON, JSONL, Parquet, or Excel. Backed by a single Polars engine with full read_options/write_options passthrough.
- Robust by Default: Fail-fast validation with clear errors (invalid engine names, missing paths, directories, encrypted PDFs), graceful handling of empty files, no
UnicodeDecodeError when constructing a reader over a non-UTF-8 file, and sane comment semantics — only leading # lines are treated as comments, so #-prefixed data rows such as hex colors are preserved on all engines.
- PDF Parsing, OCR & Corpus Bundles: Read PDFs into a typed document of headings, paragraphs, key-value pairs, tables, lists, and figures — as DataFrames, Arrow tables, dicts, Markdown, or SQL — and write JSON, JSONL, Markdown, Parquet, CSV, images, checksummed single-document bundles (
write_bundle, render_pages="vision_only"), or parallel multi-document corpora (extract_corpus, load_corpus). Hidden text is flagged, never dropped, and scanned pages are read with optional Tesseract OCR. Powered by the permissively-licensed PDFium engine with an in-process zero-subprocess fast path (sandbox=False) and optional process-isolated sandboxing (sandbox=True).
- Schema-Driven PDF Rationalization (v5.1+): Extract one or many Pydantic schemas across PDF documents, bundles, or corpora (
rationalize(), rationalize_many(), PassSpec) with adaptive section coalescing, automatic unit bisection on output truncation (split_on_truncation=True), multimodal VLM routing and cross-family scan grounding (multimodal=True), normalized identity keys (Key(normalizer="alnum_upper")), non-disputing Informational fields, cross-family consensus (min_families=2), 3-witness quote & key grounding, cross-unit entity folding (fold_across_units=True), provenance-by-default atomic JSONL & DataFrame exports (to_jsonl(), to_dataframe(), telemetry.to_dict()), up to 256 concurrent in-flight requests with live telemetry (event_delivery="live"), and offline cloud batch execution (prepare_batch, ingest_batch).
- Pythonic API: Enjoy a clean and intuitive API that integrates seamlessly into your existing Python workflows.
Powertools Under The Hood
| Tool |
Description |
| Rust / PyO3 |
Bundled native extension (datagrunt._native, abi3) that powers CSV delimiter & dialect inference; shipped as platform wheels and validated for byte-for-byte parity against a pure-Python reference |
| DuckDB |
Fast in-process analytical database with excellent SQL support |
| Polars |
Multi-threaded DataFrame library written in Rust, optimized for performance |
| PyArrow |
Python bindings for Apache Arrow with efficient columnar data processing |
| PDFium |
The PDF engine (via pypdfium2) — permissively licensed (BSD-3 / Apache-2.0); text, vector rules, images, and page renders |
| Pillow |
Image encoding and OCR preprocessing for PDF pages (MIT-CMU) |
| Tesseract |
OCR for scanned/image-only pages, run as the system tesseract program (optional) |
Installation
We recommend using uv as the default package manager.
To install Datagrunt using uv:
uv pip install datagrunt
Datagrunt 5.x supports Python 3.11–3.15 (requires Python 3.11 or newer).
PDF parsing is an optional extra — install it with uv pip install "datagrunt[pdf]". For schema-driven PDF extraction (rationalize), install uv pip install "datagrunt[pdf,rationalize]". See PDF parsing and Schema-driven extraction (rationalize) below.
Quick Start
Reading CSV Files with Multiple Engine Options
from datagrunt import CSVReader
from pathlib import Path
# Load your CSV file with different engines
# Accepts both string paths and Path objects
csv_file = 'electric_vehicle_population_data.csv'
csv_path = Path('electric_vehicle_population_data.csv')
# Choose your engine: 'polars' (default), 'duckdb', or 'pyarrow'
reader_polars = CSVReader(csv_file, engine='polars') # String path - fast DataFrame ops
reader_duckdb = CSVReader(csv_path, engine='duckdb') # Path object - best for SQL queries
reader_pyarrow = CSVReader(csv_file, engine='pyarrow') # Arrow ecosystem integration
# Get a sample of the data (streams the first rows — the whole file is never
# materialized, so sampling large files stays memory-bounded on every engine)
reader_duckdb.get_sample()
DuckDB Integration for Performant SQL Queries
from datagrunt import CSVReader
# Set up DuckDB engine for SQL capabilities
dg = CSVReader('electric_vehicle_population_data.csv', engine='duckdb')
# Construct your SQL query using the auto-generated table name
query = f"""
WITH core AS (
SELECT
City AS city,
"VIN (1-10)" AS vin
FROM {dg.db_table}
)
SELECT
city,
COUNT(vin) AS vehicle_count
FROM core
GROUP BY 1
ORDER BY 2 DESC
"""
# Execute the query and get results as a Polars DataFrame
df = dg.query_data(query).pl()
print(df)
With the DuckDB engine, datagrunt imports the CSV once per reader or writer and
reuses it: repeated reads (to_dataframe, to_arrow_table, get_sample),
query_data calls, and multi-format exports (write_csv + write_excel +
write_json + write_parquet) all skip re-importing the file, so follow-up
operations run dramatically faster.
You never have to manage this — the connection is released automatically when the
reader or writer goes out of scope (its connection is reference-counted). If you
want to release it early (for
example, to free memory deterministically in a long-running process), use the
reader as a context manager or call close(); this is optional and the object
stays usable afterward:
with CSVReader('vehicles.csv', engine='duckdb') as dg:
df = dg.query_data(f"SELECT city, COUNT(*) FROM {dg.db_table} GROUP BY 1").pl()
# connection released here, even if the block raises
Consistent Column Names with normalize_columns
Pass normalize_columns=True at construction to work in normalized column names (lowercase, underscores, collision-safe) everywhere — including SQL:
from datagrunt import CSVReader
dg = CSVReader('electric_vehicle_population_data.csv', engine='duckdb', normalize_columns=True)
# The DuckDB table is imported with normalized names, so you write your
# query and read your results in the same vocabulary — no aliases needed.
query = f"SELECT city, vin_1_10 FROM {dg.db_table} LIMIT 5"
df = dg.query_data(query).pl()
# Every other output honors the same setting
dg.to_dataframe() # columns: city, vin_1_10, ...
dg.get_sample() # same normalized names
CSVWriter(..., normalize_columns=True) does the same for every exported file. The older per-call form (to_dataframe(normalize_columns=True)) still works but is deprecated and emits a DeprecationWarning.
Exporting Data to Multiple Formats
from datagrunt import CSVWriter
from pathlib import Path
# Create writer with your preferred engine (accepts both strings and Path objects)
input_file = Path('input.csv')
writer = CSVWriter(input_file, engine='duckdb') # Default for exports
# Export to various formats
writer.write_csv('output.csv') # Clean CSV export
writer.write_excel('output.xlsx') # Excel workbook
writer.write_json('output.json') # JSON format
writer.write_parquet('output.parquet') # Parquet for analytics
# Use PyArrow engine for optimized Parquet exports
writer_arrow = CSVWriter('input.csv', engine='pyarrow') # String path also works
writer_arrow.write_parquet('optimized.parquet') # Native Arrow Parquet
Every write_* method — including write_parquet — honors lenient=True for
ragged CSVs, and empty source files produce empty output instead of an error.
Reading and writing Excel
ExcelReader and ExcelWriter read .xlsx/.xls-family workbooks sheet by
sheet. Reading is backed by a single canonical engine — Polars + calamine
(via fastexcel, a core dependency) — so there is no engine argument. A
non-Excel or missing path is rejected at construction (ValueError /
FileNotFoundError).
from datagrunt import ExcelReader, ExcelWriter
xl = ExcelReader("workbook.xlsx")
xl.sheets # ['Sheet1', 'Sheet2', ...]
xl.to_dataframe() # first sheet as a Polars DataFrame
xl.to_dataframe(sheet="Sheet2") # by name
xl.to_dicts(sheet=1) # by position
xl.to_arrow_table() # also: get_sample(), all accept sheet=
xl.query_data(f"SELECT * FROM {xl.db_table}", sheet="Sheet2")
# Read options are keyword arguments forwarded verbatim to pl.read_excel
# (constructor default or per call). Pass any pl.read_excel parameter:
xl.to_dataframe(has_header=False)
xl.to_dataframe(read_options={"skip_rows": 2, "n_rows": 100})
w = ExcelWriter("workbook.xlsx")
w.write_csv("out.csv") # first sheet
w.write_parquet("out.parquet", sheet="Sheet2")
w.write_csv("out.csv", all_sheets=True) # one file per sheet: out_Sheet1.csv, ...
w.write_excel("all.xlsx", all_sheets=True) # one multi-tab workbook
Every reader/writer method takes an optional sheet= (name or zero-based
index), defaulting to the first sheet; an invalid sheet raises a ValueError
listing the available sheets, and empty/blank workbooks return empty results.
The keys source, sheet_id, and sheet_name are reserved (sheet selection is
controlled via sheet=).
normalize_columns=True (constructor or per call) normalizes column names
exactly as the CSV API does. Values beginning with =, +, -, @ are
written verbatim — sanitize at the application layer if your source is
untrusted and the output may be opened in a spreadsheet (CWE-1236).
How read options work (same for Excel and Parquet). In both subsystems
you pass read options as keyword arguments, and Datagrunt forwards them
verbatim to the underlying Polars function — pl.read_excel for Excel,
pl.read_parquet for Parquet. The mechanism is identical; only the
available option names differ, because the two Polars functions differ.
pl.read_excel happens to expose a parameter that is itself a dict named
read_options (the calamine engine's option bag, where skip_rows/n_rows
live), which is why you see read_options={...} above. pl.read_parquet has
no such dict — its options (columns, n_rows, …) are plain top-level
parameters. So xl.to_dataframe(read_options={"skip_rows": 2}) and
pq.to_dataframe(columns=["id"], n_rows=100) use the same Datagrunt
keyword-passthrough; the shape of the arguments comes straight from Polars.
Reading and writing Parquet
ParquetReader and ParquetWriter work with .parquet files as a
single-table columnar format — there are no sheets and no engine argument.
Reading is backed by a single canonical Polars engine. A non-Parquet or missing
path is rejected at construction (ValueError / FileNotFoundError).