Reading and writing files
Last updated
Real data arrives in files, and files are rarely exactly what read_csv expects. In this lesson you'll learn the read_csv options that fix most problems, read JSON, save a clean table without an extra column, and deal with the error that every analyst in the Philippines meets sooner or later: a file whose ñ won't read.
By the end of this lesson you can
- Read a CSV with the right
sep,na_valuesandparse_dates - Read a JSON file into a table
- Save a table with
to_csv(index=False), and say whyindex=False - Fix a
UnicodeDecodeErrorby giving the file’s encoding
The options that matter
A store sends its kilos in a file that uses semicolons, and a dash where it didn't report. Step through what read_csv makes of it with each option:
Now run it. The file is in the notebook's data folder.
The options you'll use most:
| option | what it says | example |
|---|---|---|
sep | what's between values | sep=";", or sep="\t" for tabs |
na_values | extra text that means missing | na_values=["-", "none"] |
parse_dates | columns to read as dates | parse_dates=["date"] |
dtype | a column's type, decided by you | dtype={"code": "str"} |
encoding | how the text is stored | encoding="cp1252", step 4 |
pandas already treats an empty value, NA, n/a and NaN as missing, and a few more. na_values adds to that list.
dtype matters for codes that look like numbers. A barangay or ZIP code such as 0410 read as a number becomes 410, and the leading zero is gone for good. dtype={"code": "str"} keeps it as text.
JSON, Excel and Parquet
Data from websites often comes as JSON: a list of records, each like a Python dictionary. pd.read_json reads it into a table. Run it.
Two other formats you'll meet:
- Excel:
pd.read_excel("sales.xlsx", sheet_name="January")reads one sheet;sheet_name=Nonereads them all, as a dictionary of tables. It needs theopenpyxlpackage installed. - Parquet:
df.to_parquet("sales.parquet")andpd.read_parquet(...). A file format built for tables: much smaller than CSV, much faster to read, and it keeps the dtypes, so dates stay dates. It needspyarrow. Use it for your own in-between files; use CSV when people need to open the file in a spreadsheet.
Neither package runs inside this page, so try those two on your own computer. pip install openpyxl pyarrow in your project's environment, as in lesson 1.4.
Saving a table
Saving is one line. Run the cells, and compare the two files.
The first file starts date,store,kilos,price, like the one you read. The second starts with a comma: ,date,store,kilos,price, and every row with a number, 0,, 1,, 2,. That's the index, which to_csv saves unless you say index=False.
Read it back and you get a column called Unnamed: 0 that nobody asked for. Save and load a few times and you have Unnamed: 0.1 as well. So: index=False, unless the index holds real information, such as store names.
Remember the rule from lesson 1.5: write to data/clean/, never over the file in data/raw/.
Wrong way: the ñ that won’t read
A list of branches arrives from an old office computer. The first cell makes that file (a real one would just arrive), and shows its first 30 bytes. Run both cells.
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1. Look at the bytes in the first cell: Para\xf1aque. The ñ is stored as one byte, f1. That's how Windows-1252 (cp1252), the encoding many older Windows programs use, writes ñ.
pandas reads files as UTF-8 unless you say otherwise. UTF-8 writes ñ as two bytes, c3 b1, and f1 on its own isn't valid UTF-8, so reading stops. (Some programs don't stop: they guess, and give you Parañaque or Para単aque, and you might not notice until the report is printed.)
The fix is to say what the file really is:
Parañaque, Las Piñas, Dasmariñas: any Philippine place name with ñ will show this up. When a file won't read, try encoding="cp1252"; when it reads but the letters are wrong, look for à in the text. And when you save, use UTF-8 (the default), so the next person doesn't meet the same problem.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- pandas: IO tools, CSV and text files: every read_csv option
- pandas: pandas.read_csv: sep, na_values, parse_dates, dtype and encoding
- pandas: pandas.DataFrame.to_csv: the index argument
- pandas: pandas.read_json: reading a list of records
- The Python Standard Library: codecs, Standard Encodings: the names of encodings, cp1252 among them