Reading a CSV File
The read_csv function reads a CSV file into a DataFrame. A CSV file holds a table as plain text with commas between values.
Read a small CSV
This CSV text holds three rows. The first row names the columns.
import io
import pandas as pd
small_csv = """order_id,product,units
101,Tea,2
102,Coffee,1
103,Mug,3"""
df = pd.read_csv(io.StringIO(small_csv))
print(df)A CSV with prices
The same shape works for other columns. This file holds products, categories, and prices.
import io
import pandas as pd
small_csv = """product,category,price
Tea,Drink,4.50
Coffee,Drink,6.00
Mug,Home,12.00
Notebook,Office,8.50"""
df = pd.read_csv(io.StringIO(small_csv))
print(df)Example
import io
import pandas as pd
SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales)Key points
- Use pd.read_csv to read a CSV file.
- Use io.StringIO to turn CSV text into something read_csv can read.
- The first row of the file becomes the column names.
- Each later row becomes one row of the DataFrame.
- Print the result to see the whole table.
In this example, the sales table sits in a text variable named SALES_CSV. The io.StringIO call turns that text into something read_csv can read. The read_csv call turns it into a DataFrame named sales. The print shows all twelve rows.
Note
A CSV file is plain text, so it opens in any text editor.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which function reads a CSV file into a DataFrame?