Two messy CSV files enter a Python ETL pipeline, which produces a clean spreadsheet and a separate file for flagged rows.

Build a Python ETL Pipeline From Scratch (With CSVs)

In this article, we focus on how to build a Python ETL pipeline that is efficient and effective.

The first time you open two “standard” sales exports and discover they have different ideas about what a number looks like, ETL starts to make a lot more sense.

I wanted a small example that shows what happens between someone dropping a file in a folder and someone else trusting the number on a dashboard. So I put together two fictional sales exports, five rows total. One order shows up twice. One amount says N/A. And the same region is written in more than one way. Sound familiar?

The goal: combine the files into one clean CSV and keep a second CSV that explains exactly what didn’t make it in.

Understanding the process of a Python ETL pipeline is crucial for data management.

The importance of a well-structured Python ETL pipeline cannot be overstated.

The result: 5 rows read, 3 kept, 2 flagged, and $259.75 in clean sales.

What the pipeline does

If you’re coming from ETL vs. ELT vs. Dataflows, this is the ETL approach in miniature:

  1. Extract: Read both monthly sales CSVs from an input folder.
  2. Transform: Clean up the region names, parse the dates and amounts, and check for duplicate order IDs.
  3. Load: Write one CSV for reporting and another for review.

“Load” means writing to a CSV in this demo. The same cleaned rows could go into a database, but a file makes it easy to see exactly what changed. Everything here runs with Python 3.9 or newer and its standard library. No packages to install.

Start with two messy CSVs

Save these in an input folder next to etl.py. The filenames use year and month so Python’s alphabetical sort processes January before February.

A Python ETL pipeline allows us to efficiently manage data extraction and transformation.

Creating a Python ETL pipeline can significantly enhance your data processing capabilities.

With a Python ETL pipeline, you can automate the data handling process.

Each step in the Python ETL pipeline is designed for optimal performance.

By utilizing a Python ETL pipeline, you can ensure data integrity throughout the process.

A robust Python ETL pipeline can handle various data formats efficiently.

To build a Python ETL pipeline, understanding data transformation is essential.

input/sales_2026-01.csv
				
					order_id,order_date,region,amount
1001,2026-01-20, north ,$125.50
1002,2026-01-28,SOUTH,89.00
				
			
input/sales_2026-02.csv
				
					order_id,order_date,region,amount
1002,2026-01-28,south,$89.00
1003,2026-02-04,East,N/A
1004,2026-02-08,west,45.25
				
			

After a little cleanup, the two versions of order 1002 describe the same sale. I want it counted once. For order 1003, I don’t know what the amount should be. Turning N/A into zero would make the file look clean while hiding the problem.

Write the pipeline

Python’s csv.DictReader and DictWriter let me work with named columns, and Decimal keeps the sample’s currency calculations in decimal arithmetic. In this demo, the files share a header, use ISO-style dates and assume one row per order.

Save this as etl.py:

Transforming data is a critical step in a Python ETL pipeline.

The loading phase of the Python ETL pipeline is where the cleaned data is saved.

Building a Python ETL pipeline involves carefully planning each step.

				
					import csv
from datetime import date
from decimal import Decimal, InvalidOperation
from pathlib import Path

FIELDS = ["order_id", "order_date", "region", "amount"]
CENT = Decimal("0.01")
files = sorted(Path("input").glob("sales_*.csv"))
if not files:
    raise SystemExit("No sales_*.csv files found in input/")

accepted = {}
rejected = []
rows_read = 0

for path in files:
    with path.open(encoding="utf-8-sig", newline="") as source:
        reader = csv.DictReader(source)
        if reader.fieldnames != FIELDS:
            raise SystemExit(f"Unexpected header in {path.name}")

        for line, raw in enumerate(reader, start=2):
            rows_read += 1
            try:
                if None in raw or any(raw[key] is None for key in FIELDS):
                    raise ValueError("wrong number of columns")
                order_id = raw["order_id"].strip()
                region = raw["region"].strip().upper()
                if not order_id or not region:
                    raise ValueError("missing order ID or region")
                order_date = date.fromisoformat(raw["order_date"].strip())
                amount = Decimal(raw["amount"].strip().removeprefix("$"))
                if not amount.is_finite() or amount != amount.quantize(CENT):
                    raise ValueError("amount must be finite and use whole cents")

                clean = dict(order_id=order_id, order_date=order_date.isoformat(),
                             region=region, amount=f"{amount:.2f}")
                if order_id in accepted:
                    reason = ("duplicate order" if accepted[order_id] == clean
                              else "conflicting order ID; review both rows")
                    raise ValueError(reason)
                accepted[order_id] = clean
            except (ValueError, InvalidOperation) as error:
                reason = ("invalid amount" if isinstance(error, InvalidOperation)
                          else str(error))
                rejected.append({**{key: raw[key] for key in FIELDS},
                                 "source": path.name, "record": line - 1,
                                 "reason": reason})

assert rows_read == len(accepted) + len(rejected)
Path("output").mkdir(exist_ok=True)

def write_csv(name, fields, rows):
    with Path("output", name).open("w", encoding="utf-8", newline="") as target:
        writer = csv.DictWriter(target, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)

write_csv("sales_clean.csv", FIELDS, accepted.values())
write_csv("sales_rejected.csv", FIELDS + ["source", "record", "reason"], rejected)

total = sum((Decimal(row["amount"]) for row in accepted.values()), Decimal("0.00"))
print(f"Read {rows_read} | Kept {len(accepted)} | Rejected {len(rejected)}"
      f" | Clean total: ${total:,.2f}")
				
			

From the folder containing etl.py, run:

Using a Python ETL pipeline allows for flexibility in data management.

By refining your Python ETL pipeline, you can achieve better data quality.

				
					python3 etl.py




				
			

Check what made it through

Regular checks in your Python ETL pipeline will help maintain data accuracy.

				
					Read 5 | Kept 3 | Rejected 2 | Clean total: $259.75
				
			
OrderWhat happened
1001Kept. north became NORTH and $125.50 became 125.50.
1002Kept once at 89.00. The second copy went to the review file.
1003Flagged. The source gave us N/A, so it didn’t contribute to the total.
1004Kept at 45.25.

The effectiveness of a Python ETL pipeline can be measured by its output consistency.

Open output/sales_clean.csv for the reporting rows. Open output/sales_rejected.csv to see what was flagged, where it came from, and why. The row counts tie out: 5 = 3 + 2. The dollar total covers only the clean rows; we still don’t know the missing amount.

The rule I’d clarify before using this at work

The demo keeps the first valid row for each order ID. If a later row has the same ID but different details, it gets flagged for review. That’s a rule I chose for this example. If a second row represents a legitimate line item, the key needs both an order ID and a line ID. If a later file is a correction, the business has to decide which record wins.

That’s the part I’d want to talk through before anyone scheduled this to run overnight. I’d also make conflicting records a stop-and-review condition before a financial report went out. A script that finishes and a number you can defend are two different things.

What I’d try next

I’d run these same files through Power Query and compare what it takes to handle the duplicate, keep a review file, and rerun the process next month. Same messy files, same rules. That makes it a fair comparison.

If you build reporting pipelines, what’s one data check you insist on running before anyone sees the dashboard? I’d love to hear what’s saved you from a bad refresh.

Documentation of the Python ETL pipeline process is vital for future reference.

A well-documented Python ETL pipeline facilitates easier troubleshooting.

Start with two messy CSVs.
Python ETL Pipeline FAQs

What are the three steps in a Python ETL pipeline?

Extract reads the source files, transform cleans and validates the data, and load writes the result somewhere useful. In this demo, Python reads two sales CSVs and writes a clean reporting file plus a separate review file. Microsoft’s ETL overview explains how those steps work in larger systems.

Do I need pandas to build this ETL pipeline?

No. This demo uses Python 3.9 or newer and only standard-library modules. Python’s built-in CSV module reads and writes rows by column name, and Decimal handles the sales amounts without the small rounding artifacts you can get with binary floats.

Can I add another month of sales without changing the code?

Yes. Save the new file in input/ with the same column names and order, and name it something like sales_2026-03.csv. Run the script again. It rereads all matching files and replaces both output CSVs, so you don’t need to append the new month by hand.

What happens if two rows have the same order ID but different amounts?

The demo keeps the first valid row and flags the later one for review. It doesn’t assume the newer amount is correct. If your export has multiple line items per order, use the order ID and line ID together before treating a repeated order ID as a duplicate.

Should I use Python or Power Query for this?

I’d start with Power Query if the work stays in Excel or Power BI and the team wants to maintain it in a visual editor. I’d choose Python if I want a standalone script, automated tests, or a separate review file as part of the run. Either way, I’d check that every input row is accounted for before I trust the total.

Many organizations rely on a Python ETL pipeline for their data processing needs.

Understanding how to optimize a Python ETL pipeline is key for performance improvement.

Exploring various libraries can enhance your Python ETL pipeline capabilities.

Keeping your Python ETL pipeline adaptable is crucial as data needs evolve.

Consider scalability when designing your Python ETL pipeline.

Efficient data handling through a Python ETL pipeline can lead to better decision-making.

A complete understanding of a Python ETL pipeline is beneficial for all data professionals.

Regularly updating your knowledge on Python ETL pipeline techniques is recommended.

Continuous improvement of your Python ETL pipeline will yield better results over time.

Same messy data. Two ways to clean it.

You’ve seen how Python handles the duplicate order and the missing amount. Next, I’ll run the same files through Power Query and show where each tool makes the job easier. Subscribe for more runnable code, sample files, and step-by-step builds you can try yourself.

Ultimately, mastering the Python ETL pipeline process sets you up for success in data management.

Send Me the Next Build
Related Articles....
Scroll to Top