Learn Python Programming  /  Import & Export  /  CSV Files

CSV Files

Python offers two common ways to work with CSV files: the built-in csv module for lightweight, row-by-row access, and pandas for full table-based analysis.

Reading a CSV with the Built-in csv Module

R Code
import csv

with open("students.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
Output
['name', 'score']
['Rafi', '88']
['Meera', '92']
💡 Tip
Every value read by the csv module comes back as a string, even numbers - notice '88' has quotes above. Convert with int() or float() before doing any math with the values.

Reading a CSV into Dictionaries

R Code
with open("students.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["score"])
Output
Rafi 88
Meera 92

Writing a CSV File

R Code
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "score"])
    writer.writerow(["Rafi", 88])
    writer.writerow(["Meera", 92])

The Easier Way: pandas

For any real data analysis, pandas is almost always the better tool - it reads a whole CSV into a table (DataFrame) in one line.

R Code
import pandas as pd

df = pd.read_csv("students.csv")
print(df)

df.to_csv("students_out.csv", index=False)
Output
    name  score
0   Rafi     88
1  Meera     92
💡 Tip
Always pass index=False to to_csv() unless you specifically want an extra unnamed column of row numbers written into the file - one of the most common CSV mistakes.

Advanced: Handling Large or Messy CSV Files

🚀 Advanced Example
pandas can read a CSV in chunks (to save memory on huge files) and lets you specify exactly which columns and types to load.
R Code
# only read specific columns, and set a custom missing-value marker
df = pd.read_csv("big_data.csv", usecols=["name","score"], na_values=["-999"])

# process a huge file in chunks of 10,000 rows at a time
for chunk in pd.read_csv("huge_file.csv", chunksize=10000):
    print(chunk.shape)

Key Points

  • The built-in csv module gives lightweight, row-by-row access; values always come back as strings.
  • pandas.read_csv() and .to_csv() are the standard tools for real data analysis work.
  • Always use index=False when writing with pandas, unless you want an extra row-number column.
  • usecols, na_values, and chunksize help handle large or messy real-world CSV files.