← Back to Pandas Course | Chapter 11: File I/O | Lesson 1 of 7

read_csv/to_csv

read_csv loads a CSV file into a DataFrame and to_csv writes one back out.

In this page:

  1. read_csv/to_csv
Syntax
python
df = pd.read_csv("file.csv", sep=",", header=0)
df.to_csv("out.csv", index=False)

read_csv/to_csv

pd.read_csv(path) reads comma-separated text, with options like sep, header, usecols, dtype, parse_dates and na_values. to_csv(path, index=False) writes a file without the row index. The path can also be a URL or an in-memory buffer.

Note: Pass index=False to to_csv unless you need the index.

Example: read_csv/to_csv

python
import io
import pandas as pd

csv = "name,age,joined\nAnn,28,2024-01-05\nBob,35,2024-02-10"
df = pd.read_csv(io.StringIO(csv), parse_dates=["joined"])
print(df)
print(df.dtypes)
print(df.to_csv(index=False))

# Output:
#   name  age     joined
# 0  Ann   28 2024-01-05
# 1  Bob   35 2024-02-10
# name              object
# age                int64
# joined    datetime64[ns]
# dtype: object
# name,age,joined
# Ann,28,2024-01-05
# Bob,35,2024-02-10
Related Topics
Common Mistakes
  1. Writing the index as an extra column
  2. Not parsing dates
  3. Loading every column when only a few are needed
Chapter Summary
  • read_csv loads CSV
  • to_csv writes it
  • usecols and dtype save memory
  • index=False skips the index
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.