File Handling in Python
Read and write CSV, Excel, and text files — the entry point of every data project
Almost every data analysis starts with reading a file. Python can read and write CSV files, Excel workbooks, JSON, text files, and more. With pandas, loading a CSV is a single line.
Knowing how to handle files well — specifying encodings, skipping bad rows, reading specific sheets — separates analysts who write robust scripts from those whose code breaks on every new dataset.
Examples
Key Points
- ✓pd.read_csv() and pd.read_excel() are the two most-used file loading functions
- ✓encoding="latin-1" fixes UnicodeDecodeError on files with Indian language characters
- ✓Always use index=False in to_csv() and to_excel() to avoid the extra index column
- ✓parse_dates=["col"] auto-converts date strings to datetime objects
- ✓ExcelWriter context manager saves multiple DataFrames to multiple sheets in one file
Practice Question
You saved a DataFrame with df.to_csv("output.csv") and notice an extra unnamed column with numbers 0,1,2... when opening in Excel. What caused this?