To automate data entry with Python, read the data where it already lives (a spreadsheet, a CSV export, a PDF or an email), clean and validate every row with pandas and Pydantic, then write it into the target system through its API, an import file or its database. Fill web forms with a browser script only when there is no other way in. Use an AI model only for unstructured documents such as invoices in many layouts, check its output with the same validation rules and send anything that fails to a person instead of letting the script guess.
The rest of this guide shows each step with short code examples, tested with pandas 3.1 and Pydantic 2.14, plus Playwright and the Anthropic Python SDK for the browser and AI steps, and how to check whether the work pays off.
What data entry can Python automate?
Most manual data entry is one of four jobs:
- Copying between systems. Exporting orders from a shop and typing them into an accounting tool, or moving leads from a spreadsheet into a CRM.
- Keying values from documents. Invoices, purchase orders, application forms and scanned letters.
- Re-typing emails. Order confirmations, booking requests and web form notifications that end up in a tracker.
- Updating the same record twice. A change of address that has to be made in the CRM, the billing tool and a shared sheet.
A good test: if a new hire could do the task from a written checklist, a script can usually do it too. The parts that need judgement stay with people, and the script hands them over.
Step 1: Map the source and the destination
Before writing code, list every field: where it comes from, what format it arrives in, where it has to go and who checks it today. Then choose how the data gets into the target system. In order of preference:
- 1The system's API. Fastest and most reliable. The system validates the data itself and every call can be logged.
- 2A bulk import. Many CRMs and accounting tools accept a CSV import. Python prepares a clean file, and a person or the script uploads it.
- 3A database you own. Write straight into the tables, inside a transaction.
- 4An Excel or Google Sheets file that people already work in.
- 5A browser script that fills the web form, when the system offers none of the above.
- 6Screen automation such as PyAutoGUI, which clicks by screen position. Keep it as a last resort: it breaks when a window moves or the layout changes.
Many business tools offer an API or a CSV import, so check their documentation before you plan anything else.
Step 2: Read the data where it starts
Spreadsheets and CSV exports
pandas reads both. Read every column as text first, then convert only the columns that should be numbers or dates. That keeps IDs such as 00123 and phone numbers intact:
import pandas as pd
orders = pd.read_csv("orders_export.csv", dtype=str)
orders.columns = orders.columns.str.strip().str.lower().str.replace(" ", "_")
orders["customer_email"] = orders["customer_email"].str.strip().str.lower()
orders["amount"] = pd.to_numeric(orders["amount"].str.replace(",", ""), errors="coerce")
orders["order_date"] = pd.to_datetime(orders["order_date"], errors="coerce").dt.dateValues that cannot be converted become empty instead of crashing the script, and the validation in Step 3 catches them.
PDFs
For PDFs with a text layer, which covers most PDFs created by software, pdfplumber extracts the text page by page (the AI example in Step 4 shows it). Scanned documents are images, so they need OCR first. The NYSCEF court records pipeline follows that order for scanned legal filings: OCR first, then the text is parsed into structured fields for review.
Emails
Python's built-in imaplib and email modules read a mailbox, and Gmail and Microsoft 365 also offer APIs. Filter by sender or subject so the script only touches the messages it is meant to process, and mark each one as processed.
Step 3: Validate every row before it is entered
This is the step that makes automated entry trustworthy. A Pydantic model describes what a valid row looks like, and every row either passes or goes to a review file with the reason:
from datetime import date
from pydantic import BaseModel, Field, ValidationError, field_validator
class Order(BaseModel):
order_id: str = Field(min_length=1)
customer_email: str
amount: float = Field(gt=0)
order_date: date
@field_validator("customer_email")
@classmethod
def looks_like_email(cls, value: str) -> str:
if "@" not in value or "." not in value.split("@")[-1]:
raise ValueError("not an email address")
return value
rows = orders.astype(object).where(orders.notna(), None).to_dict("records")
valid, rejected = [], []
for row in rows:
try:
valid.append(Order.model_validate(row))
except ValidationError as err:
rejected.append({**row, "problem": "; ".join(e["msg"] for e in err.errors())})
pd.DataFrame(rejected).to_csv("needs_review.csv", index=False)The where(..., None) line turns empty cells into None, so a missing amount or an unreadable date fails with a clear message such as "Input should be a valid number". Then add the rules your team checks by eye today: the customer must already exist, the amount must be in a normal range, the date cannot be in the future.
Step 4: Use AI only for messy documents
Rules work when the layout is fixed. When invoices arrive from dozens of suppliers, each with its own layout, a language model that reads the text is simpler than writing a parser per supplier. The Anthropic Python SDK can return output that matches a Pydantic model:
from datetime import date
import anthropic
import pdfplumber
from pydantic import BaseModel
class Invoice(BaseModel):
supplier: str
invoice_number: str
invoice_date: date
currency: str
total: float
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
def extract_invoice(path: str) -> Invoice:
with pdfplumber.open(path) as pdf:
text = "\n".join(page.extract_text() or "" for page in pdf.pages)
message = client.messages.parse(
model="claude-haiku-5-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Extract the invoice fields from this document. "
"Copy values exactly as printed and do not guess.\n\n" + text,
}],
output_format=Invoice,
)
return message.parsed_outputThe model reads, but your code keeps the final say. Run the same kind of checks as in Step 3 on every invoice: a known supplier, an invoice number that has not been entered before, a total above zero. Anything that fails goes to the review file. Start with a small, fast model and compare its results with what a person typed for a sample of real documents before you switch it on.
Two practical points before you build this:
- Cost. Each document is billed by tokens. Enter a typical document size and your monthly volume into the LLM API cost calculator to see the bill for each model first.
- Data rules. Check that sending these documents to an AI provider fits your contracts and privacy rules. Some data should stay inside your own systems.
This mix of rules, AI extraction and human review is the kind of work covered under AI workflow automation.
Step 5: Write the data where it belongs
Through the API
import os
import requests
def create_order(order: Order) -> None:
response = requests.post(
"https://api.example.com/v1/orders",
json=order.model_dump(mode="json"),
headers={"Authorization": f"Bearer {os.environ['CRM_TOKEN']}"},
timeout=30,
)
response.raise_for_status()model_dump(mode="json") turns dates into ISO strings such as 2026-11-20. Replace the URL and field names with the ones in your system's API documentation, and keep the token in an environment variable, never in the code.
Into Excel
If the destination is a workbook people keep using, openpyxl appends rows below the existing data and keeps the formatting. My guide to automating Excel reports with Python has the code in its section on entering data into an existing workbook.
Into a web form when there is no API
Playwright drives a real browser and finds fields by their labels, which survives layout changes far better than clicking screen coordinates:
from playwright.sync_api import sync_playwright
FORM_URL = "https://intranet.example.com/orders/new"
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
for order in valid:
page.goto(FORM_URL)
page.get_by_label("Order ID").fill(order.order_id)
page.get_by_label("Customer email").fill(order.customer_email)
page.get_by_label("Amount").fill(str(order.amount))
page.get_by_role("button", name="Save").click()
page.get_by_text("Order saved").wait_for()
browser.close()The sign-in step is left out; Playwright can save a logged-in session and reuse it on the next run. Waiting for the confirmation text after each save keeps the script from racing ahead of the system. Use this for internal systems and tools your account is permitted to automate.
Step 6: Make re-runs safe
A script that stops halfway must be safe to run again. Keep a record of what has been entered and skip those rows next time:
import sqlite3
db = sqlite3.connect("entered.db")
db.execute("CREATE TABLE IF NOT EXISTS entered (order_id TEXT PRIMARY KEY, entered_at TEXT)")
for order in valid:
if db.execute("SELECT 1 FROM entered WHERE order_id = ?", (order.order_id,)).fetchone():
continue
create_order(order)
db.execute("INSERT INTO entered VALUES (?, datetime('now'))", (order.order_id,))
db.commit()A row is recorded only after the target system accepted it. If the script crashes between those two lines, one row could be entered twice on the next run; when the API supports it, send the order ID as an idempotency key or look it up in the target system first to close that gap. Log every run with counts of entered, skipped and rejected rows, and send an alert when a run fails.
Step 7: Schedule it and measure the time saved
Once it works, let it run on its own. This cron line runs the script every 30 minutes from 8:00 to 18:30 on weekdays:
*/30 8-18 * * 1-5 /usr/bin/python3 /opt/data-entry/run.py >> /var/log/data-entry.log 2>&1The free cron expression generator explains any schedule in plain English, and Task Scheduler does the same job on Windows.
Then check the payoff. In the worked example in my guide on how to calculate automation ROI, one person keying 20 records a day at 5 minutes each saves 360 hours a year with 90% of the work automated, and an assumed $1,500 build pays for itself in about 9 weeks. Those numbers are an illustration; the automation ROI calculator runs the same math on yours.
What should stay manual
- Rows that fail validation, until you know why they fail and can fix the source.
- Decisions that need judgement, such as approving a refund or an unusual discount.
- Rare tasks. Work that happens a few times a year often costs more to automate than it saves.
- Spot checks. For the first weeks, compare a sample of automated entries with the source documents.
Need it built?
If your team spends hours a week copying data between tools, my business process automation service covers this work: mapping the process, building the script with validation and a review file, and scheduling it so it runs without anyone watching. Describe the task, the tools involved and how often it happens, and I will tell you whether it is worth automating.
