read_csv/to_csv
read_csv loads a CSV file into a DataFrame and to_csv writes one back out.
In this page:
Syntax
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
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
- Writing the index as an extra column
- Not parsing dates
- 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: