Claude Skills graphic design promotion

Scripting Python with Claude Code: A Practical Guide

Python scripting and Claude Code are a natural combination – Python is readable, expressive, and well-suited to the kind of automation, data processing, and tooling work that Claude Code handles well. But getting the most out of Claude Code for Python projects means understanding how to structure your prompts, how to set up your project so Claude has the right context, and which patterns work particularly well when an AI agent is doing the scripting.

This guide covers practical patterns for Python scripting with Claude Code, from first script to a complete autonomous scripting workflow.


Setting Up Your Python Project for Claude Code

The most important file for any Claude Code project is CLAUDE.md – the project manifest that Claude reads at the start of every session. For Python projects, this should include your environment setup instructions, testing approach, and any code style conventions you care about.

# CLAUDE.md

## Project Overview
Data processing scripts for customer analytics pipeline.

## Environment Setup
- Python 3.12+
- Virtual environment: source .venv/bin/activate
- Install dependencies: pip install -r requirements.txt
- Install dev dependencies: pip install -r requirements-dev.txt

## Testing
- Run tests: pytest
- Run with coverage: pytest --cov=src
- Tests live in tests/ directory, mirroring the src/ structure

## Code Style
- Black for formatting (configured in pyproject.toml)
- Ruff for linting
- Type hints required on all public functions
- Docstrings: Google style

## Key Directories
- src/ - main package code
- scripts/ - standalone scripts for one-off operations
- tests/ - pytest test suite
- data/ - input/output data (not in version control)

This gives Claude the context to make correct decisions autonomously – which Python version, where to put new files, what testing framework to use, what style to apply – without needing to be told each time.


Writing Standalone Scripts

Standalone scripts – the kind that do one thing, accept command-line arguments, and produce output – are where Python scripting and Claude Code meet most naturally. You describe what the script should do and Claude generates it, complete with argument parsing, error handling, and sensible logging.

Write a Python script at scripts/process_invoices.py that:
- Accepts a directory path as a command-line argument
- Reads all CSV files in that directory
- Extracts: invoice number, date, vendor, amount (total)
- Validates that amounts are positive numbers and dates are valid
- Writes a combined output.csv with all valid invoices
- Logs invalid records to invalid_records.log with the reason
- Prints a summary on completion: N invoices processed, M invalid

Use argparse for CLI arguments, csv module for file handling,
logging module for the log output, pathlib for file paths.

The specificity here matters. Naming the libraries you want – argparse, csv, pathlib – prevents Claude from reaching for heavier alternatives when the standard library is correct. Specifying what the output looks like removes ambiguity. Describing error handling explicitly means the script handles bad data correctly rather than crashing on the first invalid row.


Test-Driven Python with Claude Code

One of the most effective Claude Code patterns for Python is asking it to write tests first, then the implementation. This works particularly well for data transformation functions where the expected inputs and outputs are easy to specify:

Write a pytest test suite for a function called parse_invoice_row(row: dict) -> Invoice.
The function should:
- Convert the 'date' field from DD/MM/YYYY string to a datetime.date
- Convert the 'amount' field from a string like '£1,234.56' to a Decimal
- Raise ValueError if date is invalid
- Raise ValueError if amount is negative or zero
- Return an Invoice dataclass with fields: date, vendor, amount, invoice_number

Write tests covering: valid input, invalid date formats, negative amount,
zero amount, missing fields, amount with different currency symbols.

Use pytest and the standard library only (no third-party fixtures).

Claude writes the tests. You then follow up: “Now implement parse_invoice_row and the Invoice dataclass so the tests pass.” This approach produces well-tested code by default, and the tests serve as living documentation of exactly what the function is supposed to do.


Data Processing Scripts

Python’s data processing capabilities – pandas, polars, the csv module, json, sqlite3 – pair well with Claude Code’s ability to handle multi-step transformation tasks. The key is being specific about data shapes:

The file data/sales_2026.csv has columns:
date (YYYY-MM-DD), region (string), product_sku (string), 
units_sold (integer), unit_price (float), discount_percent (float)

Write a script that:
1. Loads the CSV with pandas
2. Calculates revenue per row: units_sold * unit_price * (1 - discount_percent/100)
3. Groups by region and month
4. Produces a pivot table: regions as rows, months as columns, total revenue as values
5. Saves the result to output/regional_revenue_pivot.xlsx with formatting:
   - Revenue values formatted as currency (£)
   - Totals row and totals column added
   - Region with highest revenue per month highlighted in green

Use pandas and openpyxl. Save to output/regional_revenue_pivot.xlsx

Providing the actual column names and data types eliminates a class of assumptions. Claude generates code that works with your real data rather than a generic template you’d need to adapt.


Automation Scripts with the Claude Code + n8n Pattern

Python scripts written by Claude Code integrate naturally with n8n workflows. The standard pattern: Claude Code writes and maintains the Python scripts; n8n handles the scheduling, triggering, and routing of results.

For this to work smoothly, ask Claude to write scripts that produce machine-readable output alongside human-readable output:

Write the script so it outputs a JSON summary to stdout on completion:
{
  "status": "success" | "error",
  "records_processed": N,
  "records_failed": N,
  "output_file": "path/to/output",
  "error_message": null | "string"
}

Print human-readable progress to stderr so it's captured in logs separately.

n8n’s Execute Command node captures stdout, parses the JSON, and routes accordingly – posting to Slack on success, triggering an alert on error, or passing the output file path to a subsequent upload step.


Refactoring and Extending Existing Scripts

Claude Code is as effective for working on existing Python scripts as for writing new ones. For refactoring, the clearest prompts are specific about what to change and why:

Read scripts/process_invoices.py.
The script currently reads all files into memory before processing them.
Refactor it to process files one at a time using a generator pattern,
so memory usage stays constant regardless of how many files are in the input directory.
Add a progress indicator using tqdm.
Keep the existing CLI interface and output format unchanged.

Specifying what should stay the same (“keep the existing CLI interface”) is as important as specifying what should change. It tells Claude the boundary of the refactor and prevents it from making additional changes you didn’t ask for.


The Python Claude Code Skill

For teams that do a lot of Python work with Claude Code, encoding your Python conventions in a skill file means you don’t have to specify them in every prompt. Create .claude/skills/python/SKILL.md with your standard library preferences, type hinting requirements, preferred data processing libraries, testing conventions, and output format standards. Claude reads it before working on any Python task and applies your conventions automatically.


Python scripting with Claude Code rewards specificity. The more precisely you describe the data shapes, the libraries to use, the output format, and the error handling requirements, the more accurate and usable the resulting script is on the first attempt. Claude Code can iterate on feedback – but a well-specified prompt produces code that needs less iteration, which is the point. Describe what you need clearly, set up your CLAUDE.md with your Python environment, and Claude handles the implementation.


Leave a Reply