How to Parse CSV Correctly in Python and JavaScript
CSV looks like the simplest format there is: lines, split by commas. That is exactly why so much CSV code is broken. Real files contain commas inside values, quotes, line breaks inside cells and invisible byte order marks. This guide shows what goes wrong with split(',') and how to parse and write CSV correctly in Python and JavaScript. Every output below comes from running the code on this test file:
id,name,note
1,"Smith, Ann","said ""hi"""
2,Bob,"line one
line two"
3,Zoë,It’s completely valid CSV (the format is described in RFC 4180): a value containing a comma, quote or line break is wrapped in double quotes, and a quote inside a value is written twice ("").
Why split(',') fails
text.split('\n')[1].split(',')
// [ '1', '"Smith', ' Ann"', '"said ""hi"""\r' ]- “Smith, Ann” is cut into two columns.
- The quotes stay in the data.
- Splitting by lines breaks row 2, whose note spans two lines.
- Files from Windows end lines with
\r\n, so the last value of every row ends with an invisible\r.
The fix is always the same: use a real CSV parser. Every language has one.
Python: the csv module
import csv
with open("data.csv", newline="", encoding="utf-8-sig") as f:
for row in csv.DictReader(f):
print(row)
# {'id': '1', 'name': 'Smith, Ann', 'note': 'said "hi"'}
# {'id': '2', 'name': 'Bob', 'note': 'line one\nline two'}
# {'id': '3', 'name': 'Zoë', 'note': ''}Two arguments matter more than they look:
newline=""lets the csv module handle line endings itself. Without it, line breaks inside quoted values can be read wrong, and on Windows the writer produces a blank line after every row.encoding="utf-8-sig"removes the byte order mark (BOM) that Excel adds when saving “CSV UTF-8”. With plainutf-8, the first column name becomes'id'instead of'id', androw["id"]raises aKeyErroreven though the header clearly says “id”.
row["id"] throws KeyError: 'id' but the file starts with id, print list(row.keys()). A 'id' means a BOM: switch to encoding="utf-8-sig".Writing CSV correctly – the writer adds quotes where needed:
with open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["id", "name", "note"])
w.writerow([1, "Smith, Ann", 'said "hi"'])
# file content: 'id,name,note\r\n1,"Smith, Ann","said ""hi"""\r\n'Not sure about the delimiter? csv.Sniffer().sniff(sample).delimiter detects it – for "a;b;c\n1;2;3" it returns ;, the default in many European versions of Excel.
Python: pandas
import pandas as pd
df = pd.read_csv("data.csv") # handles quotes, line breaks and the BOM
df = pd.read_csv("data.csv", dtype={"id": str}) # keep IDs as text
df = pd.read_csv("data.csv", sep=None, engine="python") # guess the delimiterpandas converts columns that look numeric into numbers. That’s convenient, until a ZIP code 02134 becomes 2134 or a product code 007 becomes 7. Pass dtype=str for any column that is an identifier rather than a quantity.
JavaScript: Papa Parse
import Papa from 'papaparse' // npm install papaparse
const result = Papa.parse(text, { header: true, skipEmptyLines: true })
result.data[0] // { id: '1', name: 'Smith, Ann', note: 'said "hi"' }
result.data[1] // { id: '2', name: 'Bob', note: 'line one\nline two' }
result.errors // [] – always check this arrayPapa Parse strips the BOM, handles \r\n, auto-detects the delimiter and works in the browser and Node.js. It can also stream huge files with step or chunk callbacks.
Papa.parse('id,price\n007,1.50\n', { header: true, dynamicTyping: true }).data[0]
// { id: 7, price: 1.5 } ← the leading zeros are gone
Papa.unparse([{ id: 1, name: 'Smith, Ann', note: 'said "hi"' }])
// 'id,name,note\r\n1,"Smith, Ann","said ""hi"""'dynamicTyping: true has the same trap as pandas: it turns 007 into 7. Leave it off, or convert only the numeric columns yourself.Checklist for robust CSV handling
- Never split by commas or lines – use a parser.
- Read with UTF-8, and strip the BOM (
utf-8-sigin Python; Papa Parse does it automatically). - Expect the delimiter to be a semicolon in files from many European Excel installations.
- Keep IDs, ZIP codes and phone numbers as strings.
- Check for rows with the wrong number of columns (
result.errorsin Papa Parse, or comparelen(row)in Python). - Write with a CSV writer so quotes are added for you.
Opening a CSV in Excel and seeing everything in one column? That’s a delimiter or encoding problem – see why your CSV opens in one column. For duplicates, stray spaces and empty rows, see how to clean a messy CSV file.
No code needed for a one-off job: the CSV Cleaner fixes headers, spaces, duplicates and delimiters, and CSV to JSON turns rows into objects with proper quote handling.