Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 06 / Topic 7 of 7

Other enterprise formats

CSV is the friendly case. Enterprises will also hand you XML feeds and fixed-width files from systems older than you:

# examples/03_enterprise_formats_xml_and_fixed_width.py
import xml.etree.ElementTree as ET   # for untrusted XML, use defusedxml (the Python docs warn about XML attacks)

xml_feed = """<shipments>
  <shipment id="S-4001"><status>DELIVERED</status><weight unit="kg">75</weight></shipment>
  <shipment id="S-4002"><status>in transit</status><weight unit="lbs">220</weight></shipment>
</shipments>"""
TO_KG = {"kg": 1.0, "lbs": 0.45359237}
for el in ET.fromstring(xml_feed).iter("shipment"):
    w = el.find("weight")
    unit = w.get("unit")
    if unit not in TO_KG:                          # never silently assume a unit
        print("quarantine:", el.get("id"), "unknown unit", unit); continue
    kg = float(w.text) * TO_KG[unit]
    print("xml:", el.get("id"), el.findtext("status").strip().lower().replace(" ", "_"), round(kg, 2))

# Fixed-width: each field sits at fixed character positions (common in older systems)
LAYOUT = [("shipment_id", 0, 6), ("status", 6, 18), ("weight_kg", 18, 24)]   # from Acme's file spec
lines = ["S-5001delivered    120.0",
         "S-5002in_transit    85.5"]
assert all(len(line) == 24 for line in lines), "line length does not match the layout"
for line in lines:
    rec = {name: line[a:b].strip() for name, a, b in LAYOUT}
    rec["weight_kg"] = float(rec["weight_kg"])
    print("fixed-width:", rec)
# A layout that is off by one character silently truncates values: always check line length and a known row.
# xml: S-4001 delivered 75.0
# xml: S-4002 in_transit 99.79
# fixed-width: {'shipment_id': 'S-5001', 'status': 'delivered', 'weight_kg': 120.0}
# fixed-width: {'shipment_id': 'S-5002', 'status': 'in_transit', 'weight_kg': 85.5}

Two more you will meet: Excel (pd.read_excel; beware merged cells, hidden sheets, and dates that arrived as serial numbers) and SFTP file drops — a folder where files appear on a schedule. For drops, the rules are: never process a file that is still being written (wait for a done-marker or a stable size), archive what you processed, and make the processing idempotent, because the same file will appear twice.

Done here? The practice set for Part 6 — 4 exercises with solutions — is on the part page.

Search the guide