Why Excel Breaks Your Python CSV (1-Word UTF-8 BOM Fix)

Your Python CSV looks completely clean in VS Code and the terminal—then you double-click it in Microsoft Excel and see Café, €50, or broken non-ASCII text.

Why? When Excel opens a CSV file directly, it expects a UTF-8 BOM (Byte Order Mark) to recognize UTF-8. Without it, Excel falls back to a legacy local codepage.

1. The Problem: Standard encoding="utf-8"

import csv

rows = [
    ["Item", "Price", "City"],
    ["Café Latte", "€5", "Seoul"],
]

with open("report_broken.csv", "w", encoding="utf-8", newline="") as f:
    csv.writer(f).writerows(rows)

# Excel opens this as: Café Latte, €5, Seoul

2. The 1-Word Fix: encoding="utf-8-sig"

import csv

rows = [
    ["Item", "Price", "City"],
    ["Café Latte", "€5", "Seoul"],
]

with open("report_clean.csv", "w", encoding="utf-8-sig", newline="") as f:
    csv.writer(f).writerows(rows)

# Excel opens cleanly: Café Latte | €5 | Seoul

3. Reading Back a UTF-8 BOM CSV Safely

When reading a file that might contain a BOM, also pass encoding="utf-8-sig" so Python strips the invisible \ufeff prefix from the first column header:

with open("report_clean.csv", "r", encoding="utf-8-sig", newline="") as f:
    for row in csv.DictReader(f):
        print(row)  # clean key "Item", not "\ufeffItem"

Comments

Popular posts from this blog

Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum

C strtol Validation: Why atoi("abc") Returns 0 and How to Fix It