11  Importing and Exporting Files

11.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"},
)

11.2 Save CSV and Excel files

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

11.3 Work with paths

from pathlib import Path

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

print(input_file)
data/input.csv

11.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.