Importing and Exporting Files in Python
Real datasets rarely start out as Python code - they usually live in files such as CSV, Excel, or JSON. Pandas provides simple, consistent functions for reading these files into a DataFrame and writing a DataFrame back out.
Reading a CSV File
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head()) # first 5 rows
Reading Excel and JSON Files
df_excel = pd.read_excel("students.xlsx", sheet_name="Sheet1")
df_json = pd.read_json("students.json")
Useful Arguments While Reading
df = pd.read_csv(
"students.csv",
usecols=["Name", "Score"], # only load specific columns
index_col="Name", # use a column as the index
nrows=100 # read only the first 100 rows
)
Exporting a DataFrame
df.to_csv("output.csv", index=False)
df.to_excel("output.xlsx", index=False)
df.to_json("output.json", orient="records")
Coming Up Next
Next, you'll explore the basic functionalities every Pandas data object provides for a first look at your data.
Arguments That Fix Messy Real-World Files
Clean sample files load with a single line. Files exported from other systems usually need a few extra arguments.
import pandas as pd
df = pd.read_csv(
"sales_export.csv",
sep=";", # semicolon-separated instead of comma
encoding="latin-1", # file was not saved as UTF-8
parse_dates=["order_date"], # convert text to datetime while loading
dtype={"pincode": str}, # keep leading zeros in codes
na_values=["NA", "-", "missing"], # treat these strings as missing
thousands="," # "1,250" becomes 1250
)
print(df.dtypes)
Checking df.dtypes right after loading is a good habit. If a numeric column shows up as object, something in it, often a stray symbol or a text note, stopped Pandas from reading it as a number.
Working With Large Files in Chunks
A file bigger than your computer's memory cannot be loaded in one go. The chunksize argument returns an iterator that yields one piece at a time, so you can process and summarise as you go.
total_by_city = None
for chunk in pd.read_csv("transactions.csv", chunksize=100_000):
part = chunk.groupby("city")["amount"].sum()
total_by_city = part if total_by_city is None else total_by_city.add(part, fill_value=0)
print(total_by_city.sort_values(ascending=False).head())
Loading only the columns you need with usecols also cuts memory use a lot, and combining both techniques handles most large-file tasks on an ordinary laptop.
Writing Several Sheets and Faster Formats
To put more than one DataFrame into a single Excel workbook, use ExcelWriter. Reading and writing .xlsx files requires the openpyxl package to be installed.
with pd.ExcelWriter("report.xlsx") as writer:
summary.to_excel(writer, sheet_name="Summary", index=False)
details.to_excel(writer, sheet_name="Details", index=False)
For data you will reload in Python later, consider Parquet with df.to_parquet("data.parquet") and pd.read_parquet(). It needs the pyarrow package, stores column types so dates and categories survive the round trip, and is usually much smaller and faster than CSV. CSV is still the better choice when the file must be opened by people in spreadsheet software or by tools that do not read Parquet.
Errors You Will Meet and How to Fix Them
- FileNotFoundError: the path is relative to where the script runs, not where the file sits. Print
import os; os.getcwd()to check, or use a full path. - UnicodeDecodeError: the file uses a different encoding. Try
encoding="latin-1"or"utf-8-sig"for files saved from Excel. - Everything lands in one column: the separator is wrong. Open the file in a text editor to see whether it uses commas, semicolons or tabs (
sep="\t"). - Dates become text after export and reload: CSV has no types, so pass
parse_datesagain when reading. - Codes lose leading zeros: read ID-like columns as strings with
dtype.
Checklist after every import: look at df.shape, df.head() and df.dtypes, and count missing values with df.isna().sum() before starting any analysis.