10  Importing and Exporting Files

10.1 Read a CSV file

import pandas as pd

df = pd.read_csv(
    "data/input.csv",
    usecols=["id", "city", "value"],
    dtype={"id": "string", "city": "string"},
)

10.2 Save CSV and Excel files

df.to_csv("output/clean_data.csv", index=False)
df.to_excel("output/clean_data.xlsx", index=False)

10.3 Work with paths

from pathlib import Path

data_dir = Path("data")
input_file = data_dir / "input.csv"

print(input_file)
data/input.csv

10.4 Things to remember

  • Explicitly define important identifier columns as text.
  • Use index=False unless the index is meaningful.
  • Use pathlib instead of manually joining path strings.