Reading CSV in Python when columns and accents go wrong
A CSV may use semicolons, include a BOM or contain separators inside quoted fields. Diagnose the format before trying to clean data that was correct.
You open a CSV and every column runs together. You fix the separator, but the first column name still looks odd. Then you discover that prices are strings. These are different problems. One call to split(',') is unlikely to solve them.
A CSV combines several decisions: character encoding, field delimiters, quoting and the meaning of each value. Correct parsing comes before data cleaning.
A small file with realistic complications
This example uses only Python 3's standard library. Its content lives inside the program, so no download is required:
import csv
import io
from decimal import Decimal
raw = '\ufeffproduct;price;note\nCuaderno;12,50;"azul; tapa dura"\n'.encode('utf-8')
text = raw.decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(text, newline=''), delimiter=';')
rows = list(reader)
print(reader.fieldnames)
print(rows[0]['product'])
print(rows[0]['note'])
print(Decimal(rows[0]['price'].replace(',', '.')))['product', 'price', 'note']
Cuaderno
azul; tapa dura
12.50The Spanish sample describes a notebook. The semicolon inside "azul; tapa dura" belongs to its note. Quoting distinguishes it from the separators between columns. csv.DictReader respects that distinction; splitting each line on ; would not.
First, decode bytes into text
The encoding specifies how to interpret bytes as characters. Here the file is known to use UTF-8 and may begin with a BOM, represented by \ufeff. Decoding with utf-8-sig consumes that marker and also accepts UTF-8 without it.
Using plain utf-8 here can leave the marker attached to the first header: \ufeffproduct instead of product. Inspect repr(reader.fieldnames) when a seemingly present column produces KeyError.
Do not try encodings until one happens to avoid an exception and assume it is correct. Some accept every byte while producing the wrong text. Check the exporting system and inspect accented names. errors='ignore' may silently remove characters.
Then, parse text into rows
delimiter=';' selects semicolons. If a whole file appears as one column, check this before blaming pandas or your analysis code.
DictReader uses the first row as headers and returns one dictionary per record. It does not convert 12,50 into a number. Nor does it guarantee equal field counts: surplus fields can appear under a None key, while missing fields can produce None values.
For an actual file, use with open('sales.csv', encoding='utf-8-sig', newline='') as file: followed by csv.DictReader(file, delimiter=';'). The newline='' argument lets the CSV module handle line endings, including those within quoted fields.
Finally, interpret each column
Replacing the decimal comma with a dot works here because the file contract specifies decimal commas and no thousands separators. Apply it to the price, not the entire row: notes and names may contain legitimate commas.
A value like 1.234,50 needs an additional rule for thousands. An empty cell needs a decision too: is the price missing, or is the record invalid? Silently turning it into zero confuses an unknown price with a free product.
Decimal preserves the decimal representation and avoids introducing binary floating-point approximations at this step. A real application still needs explicit currency and rounding rules.
With pandas: the same three settings
If you will analyze the file with pandas, read_csv takes the same decisions as parameters: sep for the delimiter, encoding for the encoding and decimal for the decimal comma. The price then arrives as a number:
import io
import pandas as pd
text = 'product;price;note\nCuaderno;12,50;"azul; tapa dura"\n'
df = pd.read_csv(io.StringIO(text), sep=';', decimal=',')
print(df.dtypes['price'])
print(df.loc[0, 'note'])float64
azul; tapa duraFor a real file you would write pd.read_csv('sales.csv', sep=';', encoding='utf-8-sig', decimal=','). pandas turns the price into a float, which is fine for analysis but not for exact money arithmetic. To pick rows and columns next, continue with loc vs iloc in pandas.
Check before analyzing
Inspect exact headers, field counts and a quoted record. Verify an accented character and a decimal against the original file. For large inputs, keep rejected records with their line numbers and reasons, while avoiding unnecessary sensitive data in logs.
As an exercise, change the note to "azul, grande; tapa dura". It should remain one field. Then switch the delimiter to , and inspect the headers. Recognizing that failure pattern saves time with unfamiliar exports.
Once parsing works, continue with grouping a list of dictionaries. For other format variations, consult the csv module documentation. The goal is to explain why each value reached the correct column, not merely to open a file without an exception.