Many older tutorials still open a CSV with Python’s built-in csv module and a for loop. It works, but every value arrives as text, so you end up converting prices, dates and counts by hand.
The better route is the pandas read CSV function, pd.read_csv(). One call turns the file into a DataFrame with typed columns, and a handful of parameters fix the messy parts: leading zeros, dates, odd blanks, extra header lines and bad encodings.
In this tutorial, I’ll show you how pandas read csv works on one small orders file, then walk through the options I reach for on real exports, including the two errors almost everyone hits.
The Sample orders.csv File We’ll Read with pandas
Every example reads the same file: eight electronics orders from US customers in the first quarter of 2026. I ran the code with Python 3.12.5 and pandas 3.0.6 on Windows, from the folder that holds the file.
order_id,order_date,customer,state,zip_code,product,quantity,unit_price
1001,2026-01-05,Rachel Turner,MA,02108,Laptop,1,999.99
1002,2026-01-09,Marcus Hill,TX,78701,Monitor,2,249.99
1003,2026-01-14,Jenna Brooks,WA,98101,Headset,3,79.99
1004,2026-01-22,Tyler Ramirez,NJ,07102,Keyboard,-,59.99
1005,2026-02-03,Olivia Grant,CO,80202,Laptop,1,
1006,2026-02-11,Derek Collins,IL,60601,Monitor,1,249.99
1007,2026-02-19,Hannah Price,CT,06103,Webcam,2,89.99
1008,2026-03-02,Caleb Foster,FL,33101,Headset,4,79.99
Three rows are tricky on purpose. The Massachusetts, New Jersey and Connecticut zip codes start with a zero, order 1004 logs its quantity as a dash, and order 1005 has no unit price at all.
Those are exactly the problems real exports have. If you need to make a file like this from Python first, see how to create a CSV file in Python.
Method 1: Read a CSV File into a DataFrame with pd.read_csv() (Recommended)
This is the call you’ll use 90% of the time. Pass the file name (or a full path) and pandas reads the first row as column names:
import pandas as pd
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 100)
df = pd.read_csv("orders.csv")
print(df.head())
print(df.shape)
Output:
order_id order_date customer state zip_code product quantity unit_price
0 1001 2026-01-05 Rachel Turner MA 2108 Laptop 1 999.99
1 1002 2026-01-09 Marcus Hill TX 78701 Monitor 2 249.99
2 1003 2026-01-14 Jenna Brooks WA 98101 Headset 3 79.99
3 1004 2026-01-22 Tyler Ramirez NJ 7102 Keyboard - 59.99
4 1005 2026-02-03 Olivia Grant CO 80202 Laptop 1 NaN
(8, 8)

head() prints the first five orders with zip code 2108 instead of 02108, and shape confirms 8 rows and 8 columns.How does this code work?
pd.read_csv() scans the file, splits each line on commas and guesses a type for every column. head() returns the first five rows, and shape is a (rows, columns) tuple.
The two set_option() lines only stop pandas from hiding middle columns behind ... in a narrow console.
Look closely at the output, though. Rachel’s Massachusetts zip code shows as 2108, and order 1005’s price shows as NaN. My guide on getting the length of a pandas DataFrame covers len() and other ways to count rows.
Let’s check the types pandas guessed for the same file:
import pandas as pd
df = pd.read_csv("orders.csv")
print(df.dtypes)
print(df["zip_code"].head(3).tolist())
Output:
order_id int64
order_date str
customer str
state str
zip_code int64
product str
quantity str
unit_price float64
dtype: object
[2108, 78701, 98101]
The zip codes became int64, so the leading zeros are gone for good. quantity became a text column (str) because of the single dash, and order_date is text too.
Note: pandas 3.0 shows text columns as the str dtype instead of object. On pandas 2.x you’ll see object for the same columns, and the rest of this tutorial behaves the same.
Method 2: Pick Columns and Data Types with usecols and dtype
Use this when the file has more columns than you need, or when pandas guesses a type wrong. Same orders file, but now I load four columns and force the zip code to stay text:
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "customer", "zip_code", "unit_price"],
dtype={"zip_code": "str"},
)
print(df.head(4))
print(df.dtypes)
Output:
order_id customer zip_code unit_price
0 1001 Rachel Turner 02108 999.99
1 1002 Marcus Hill 78701 249.99
2 1003 Jenna Brooks 98101 79.99
3 1004 Tyler Ramirez 07102 59.99
order_id int64
customer str
zip_code str
unit_price float64
dtype: object

dtype={"zip_code": "str"}, Boston stays 02108 and Newark stays 07102, and only four columns load.How does this code work?
usecols takes a list of column names (or positions), and pandas skips everything else while parsing. On a wide export with 60 columns, that saves real memory and time. To list a file’s names first, see getting pandas column names.
dtype maps a column to the type you want, so pandas never tries to turn 02108 into a number. To change a type after loading, see changing a column data type in pandas.
Important: set text types for zip codes, phone numbers, account numbers and product SKUs at read time. Once pandas drops a leading zero, you can’t tell 2108 from a real four-digit code.
Method 3: Parse Date Columns While You Read the File
By default, dates stay as plain text. Pass the column names to parse_dates and you can filter or group by date right away. Here I pull every February order from the same file:
import pandas as pd
df = pd.read_csv("orders.csv", parse_dates=["order_date"])
print(df["order_date"].dtype)
feb = df[df["order_date"].dt.month == 2]
print(feb[["order_id", "order_date", "customer"]])
Output:
datetime64[us]
order_id order_date customer
4 1005 2026-02-03 Olivia Grant
5 1006 2026-02-11 Derek Collins
6 1007 2026-02-19 Hannah Price
The column is now datetime64[us], and the filter returns the three February orders: 1005, 1006 and 1007.
How does this code work?
parse_dates converts the listed columns after reading, and the .dt accessor exposes parts like month, year and day_name(). ISO dates such as 2026-01-05 parse without any hints.
For US-style dates like 01/05/2026, add date_format="%m/%d/%Y" so pandas doesn’t guess day-first. My post on converting strings to datetime in pandas covers mixed and messy formats.
Method 4: Treat Custom Placeholders as NaN with pandas na_values
pandas already treats empty cells and strings like NA, N/A, NULL and nan as missing. A dash isn’t on that list, which is why quantity loaded as text. na_values adds your own markers:
import pandas as pd
df = pd.read_csv("orders.csv", na_values=["-"],
dtype={"zip_code": "str"})
print(df["quantity"].dtype)
print(df.isna().sum()[["quantity", "unit_price"]])
revenue = (df["quantity"] * df["unit_price"]).sum()
print(f"Revenue from complete rows: ${revenue:,.2f}")
Output:
float64
quantity 1
unit_price 1
dtype: int64
Revenue from complete rows: $2,489.87
Now quantity is float64, one value is missing in each column, and the revenue from complete rows comes to $2,489.87. If you want that line total as its own column, see adding a column to a pandas DataFrame.
How does this code work?
na_values=["-"] tells the parser to store every dash as NaN. The column becomes a float because a NumPy integer column can’t hold NaN.
Multiplying two columns gives NaN for orders 1004 and 1005, and sum() skips them. To remove incomplete rows instead, read dropping rows with NaN in pandas.
Pro Tip: pass a dictionary, such as na_values={"quantity": ["-"]}, when a dash is missing data in one column but a real value in another.
Method 5: Read a CSV with a Different Delimiter Using sep
Not every “CSV” uses commas. Some systems export pipe-separated or tab-separated files. Here’s a three-row pipe file from the same order system, read with sep="|":
order_id|customer|state|product|unit_price
1001|Rachel Turner|MA|Laptop|999.99
1002|Marcus Hill|TX|Monitor|249.99
1003|Jenna Brooks|WA|Headset|79.99
import pandas as pd
df = pd.read_csv("orders_export.txt", sep="|")
print(df)
Output:
order_id customer state product unit_price
0 1001 Rachel Turner MA Laptop 999.99
1 1002 Marcus Hill TX Monitor 249.99
2 1003 Jenna Brooks WA Headset 79.99
All five columns split correctly, and the prices load as numbers.
How does this code work?
sep (alias delimiter) is the character between fields. Use sep="\t" for tab-separated files and sep=";" for semicolon files, which many European tools produce.
If you leave sep at its default comma, the whole line lands in one column. For plain text files and read_table(), see reading text files in pandas.
Method 6: Read a CSV Without a Header Row and Set an Index Column
Some exports skip the header line entirely. If you read them normally, pandas promotes the first order to column names. Pass header=None and supply your own names:
1001,Rachel Turner,MA,999.99
1002,Marcus Hill,TX,499.98
1003,Jenna Brooks,WA,239.97
import pandas as pd
cols = ["order_id", "customer", "state", "total"]
df = pd.read_csv("orders_noheader.csv", header=None,
names=cols, index_col="order_id")
print(df)
print(df.loc[1002, "customer"])
Output:
customer state total
order_id
1001 Rachel Turner MA 999.99
1002 Marcus Hill TX 499.98
1003 Jenna Brooks WA 239.97
Marcus Hill
All three orders load as data, and df.loc[1002, "customer"] returns Marcus Hill.
How does this code work?
header=None means the file has no header row, and names provides the column labels in order. index_col="order_id" moves that column into the row index, so you can look up an order by its ID.
If your file has a header but the names are ugly, keep the header and rename afterward; my guide to setting column names in pandas shows both ways. To look up rows by label, see the pandas loc indexer.
How Do You Skip Rows, Comments and Footer Lines in a CSV?
Reports from accounting or order systems often add a title, a timestamp and a total row. Here’s that kind of file, built from the same orders:
Q1 2026 Order Export
Generated 2026-04-01 by the order system
order_id,customer,state,total
1001,Rachel Turner,MA,999.99
1002,Marcus Hill,TX,499.98
# 1003 cancelled by customer
1004,Tyler Ramirez,NJ,119.98
1006,Derek Collins,IL,249.99
TOTAL,,,1869.94
Read it as-is and pandas raises ParserError: Expected 1 fields in line 3, saw 4, because the title line has one field and the data rows have four. Three parameters clean it up:
import pandas as pd
df = pd.read_csv(
"orders_report.csv",
skiprows=2, # title + generated lines
comment="#", # the cancelled-order note
skipfooter=1, # the TOTAL row
engine="python", # skipfooter needs it
)
print(df)
print(f"Sum: ${df['total'].sum():,.2f}")
Output:
order_id customer state total
0 1001 Rachel Turner MA 999.99
1 1002 Marcus Hill TX 499.98
2 1004 Tyler Ramirez NJ 119.98
3 1006 Derek Collins IL 249.99
Sum: $1,869.94

How does this code work?
skiprows=2 drops the first two lines, so the third line becomes the header. comment="#" ignores everything after a #, which removes the cancelled-order note.
skipfooter=1 drops the last line. It only works with the slower Python engine, so set engine="python" yourself; otherwise pandas switches engines and prints a ParserWarning.
The four remaining totals add up to $1,869.94, the same figure as the report’s TOTAL line, so nothing was lost.
Method 7: Read Only the First Rows or a File in Chunks
When a file is huge, you rarely need all of it at once. nrows reads a quick preview, and chunksize hands you the file in pieces. Here’s both on the same orders file:
import pandas as pd
preview = pd.read_csv("orders.csv", nrows=3)
print(preview[["order_id", "customer", "product"]])
for chunk in pd.read_csv("orders.csv", chunksize=3):
print(len(chunk), "rows, prices:", chunk["unit_price"].count())
Output:
order_id customer product
0 1001 Rachel Turner Laptop
1 1002 Marcus Hill Monitor
2 1003 Jenna Brooks Headset
3 rows, prices: 3
3 rows, prices: 2
2 rows, prices: 2
The preview shows the first three orders, and the loop gets chunks of 3, 3 and 2 rows. The second chunk counts only two prices because order 1005 has none.
How does this code work?
nrows=3 stops parsing after three data rows. With chunksize=3, read_csv() returns a reader object instead of a DataFrame, and each loop pass yields the next three rows as a DataFrame.
You’d normally total each chunk and combine the results, so the whole file never sits in memory. My guide on reading large CSV files in Python compares chunks, usecols, the pyarrow engine and Polars on a big file.
Method 8: Read a CSV File Directly from a URL
read_csv() also accepts an http or https URL, so you don’t have to download the file first. This reads the public restaurant tips dataset hosted on GitHub:
import pandas as pd
url = ("https://raw.githubusercontent.com/mwaskom/"
"seaborn-data/master/tips.csv")
tips = pd.read_csv(url)
print(tips.shape)
print(tips[["total_bill", "tip", "day"]].head(3))
Output:
(244, 7)
total_bill tip day
0 16.99 1.01 Sun
1 10.34 1.66 Sun
2 21.01 3.50 Sun
The file has 244 rows and 7 columns, and the first bill is $16.99 with a $1.01 tip.
How does this code work?
pandas downloads the file into memory and parses it like a local one, so every parameter in this tutorial still applies. For GitHub files, use the raw link, not the web page that shows the file.
Private files behind a login need requests or a cloud SDK first. To go the other way and save a DataFrame, see writing a pandas DataFrame to CSV.
Fix UnicodeDecodeError in pandas read_csv with encoding
Files saved by older Windows programs or Excel often use the cp1252 encoding, not UTF-8. pandas reads UTF-8 by default, so accented names in a customer list break the read:
import pandas as pd
try:
pd.read_csv("customers_legacy.csv")
except UnicodeDecodeError as e:
print("UnicodeDecodeError:", str(e)[:60])
df = pd.read_csv("customers_legacy.csv", encoding="cp1252")
print(df)
Output:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 29: invalid
customer_id name city
0 501 José MartÃnez San Antonio
1 502 Renée Dubois New Orleans
2 503 Zoë Clark Portland

encoding="cp1252" loads José, Renée and Zoë correctly.The error mentions byte 0xe9, which is é in cp1252. With the right encoding, all three customers load with their accents intact.
If you don’t know the encoding, try "cp1252" first for Windows files, then "latin-1". A file that starts with a byte order mark reads cleanly with "utf-8-sig".
Why Does read_csv Raise FileNotFoundError?
The other common error is a path problem. A relative path like data/orders.csv is resolved from the folder you run Python in, not the folder your script lives in:
import pandas as pd
try:
pd.read_csv("data/orders.csv")
except FileNotFoundError as e:
print("FileNotFoundError:", e)
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'data/orders.csv'
Run the script from the right folder, or pass a full path. On Windows, write it as a raw string, such as r"C:\pyguides\orders.csv", so a \n in a folder name isn’t read as a newline.
To load every CSV in a folder at once, combine pathlib.Path.glob("*.csv") with a list comprehension. For a file that should become a dictionary rather than a table, see reading a CSV into a dictionary with pandas.
Which read_csv Parameter Should You Use?
| Problem in the file | Parameter | Example |
|---|---|---|
| Too many columns | usecols | usecols=["order_id", "total"] |
| Leading zeros lost | dtype | dtype={"zip_code": "str"} |
| Dates load as text | parse_dates | parse_dates=["order_date"] |
| Custom blanks like – or ? | na_values | na_values=["-"] |
| Pipe, tab or semicolon file | sep | sep="|" |
| No header row | header, names | header=None, names=cols |
| Title, notes or total lines | skiprows, comment, skipfooter | skiprows=2, comment="#" |
| Huge file | nrows, chunksize | chunksize=100_000 |
| Accented characters fail | encoding | encoding="cp1252" |
I start every new export with a plain read_csv() and a look at dtypes, then add only the parameters the file actually needs. You’ll rarely need more than three of them on one file.
Things to Keep in Mind When You Read CSV Files in pandas
- Check
df.dtypesafter every first read; one stray character turns a number column into text. - Set
dtype="str"for IDs and zip codes before pandas strips the leading zeros. skipfooterneedsengine="python", which is slower on big files.- A
ParserError: Error tokenizing datausually means extra header lines or a wrongsep. - Use raw strings or forward slashes for Windows paths.
Once the data is loaded, these guides cover the next steps:
- Summarize data with pandas groupby aggregation
- Filter pandas rows on multiple conditions
- Write a pandas DataFrame to Excel
- Read a CSV file with NumPy
Frequently Asked Questions
How do I read a CSV file in pandas?
Import pandas and call pd.read_csv("file.csv"). It returns a DataFrame with the first row as column names.
How do I keep leading zeros when reading a CSV in pandas?
Read the column as text with dtype={"zip_code": "str"}. Without it, pandas parses the values as integers and drops the zeros.
How do I read a CSV file without a header in pandas?
Pass header=None, and add names=[...] to give the columns labels. Otherwise pandas uses the first data row as the header.
How do I read only some columns from a CSV in pandas?
Use usecols with a list of names or positions, such as usecols=["order_id", "total"]. pandas skips the other columns while parsing.
How do I fix UnicodeDecodeError in pandas read_csv?
Pass the file’s real encoding, such as encoding="cp1252" or "latin-1" for older Windows files, or "utf-8-sig" for files with a byte order mark.
Where is pandas.read_csv documented?
See pandas.read_csv() in the official pandas docs for every parameter.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn