Python tutoring online
Home

Pandas read_csv(): Read CSV Files into a DataFrame

The Pandas read_csv() function loads data from a CSV (comma-separated values) file into a DataFrame. CSV files are commonly used to exchange data between spreadsheets, databases, websites and data-analysis applications.

In this detailed tutorial, you will learn how to read a CSV file in Pandas, specify a file path, handle files without headers, choose particular columns, set data types, parse dates, deal with missing values, change delimiters and troubleshoot common errors. The examples use realistic business data and are suitable for Jupyter Notebook or a Python script.

If you are new to Pandas, first review the Pandas DataFrame guide and how to create a DataFrame. After importing a CSV, you can select rows and columns, filter records, or handle missing values.

Learn Pandas with Real Data

Want help using Python for data analysis, coursework or business projects? One-to-one tutoring can help you practise importing, cleaning and analysing datasets.

Get 1-on-1 Python Tutoring

1. What does Pandas read_csv() do?

pd.read_csv() reads tabular data stored in a CSV file and returns a Pandas DataFrame. A DataFrame has rows and columns, making the imported data easy to inspect, clean, filter, summarise and visualise.

Start by importing Pandas using its conventional alias, pd:

Python
import pandas as pd

The basic syntax is:

Python
df = pd.read_csv("file.csv")

Here, "file.csv" is the name or path of the file and df is the variable that stores the returned DataFrame. The file must be accessible from the Python environment in which the code runs.

2. Create a sample CSV file

Suppose a business has a file named sales.csv containing the following information. The first line contains the column headings.

OrderID,Product,Region,Units,UnitPrice,OrderDate
1001,Laptop,North,2,850,2026-01-05
1002,Mouse,South,10,18,2026-01-06
1003,Keyboard,North,5,42,2026-01-07
1004,Monitor,West,3,210,2026-01-08
1005,Mouse,East,8,18,2026-01-09

You can create this file using a text editor or spreadsheet application and save it as sales.csv. Make sure the file is genuinely saved with the .csv extension, rather than as an Excel workbook.

3. How to read a CSV file in Pandas

Place sales.csv in your current working directory, then run:

Python
import pandas as pd
df = pd.read_csv("sales.csv")
print(df)

Example output:

   OrderID   Product Region  Units  UnitPrice   OrderDate
0     1001    Laptop  North      2        850  2026-01-05
1     1002     Mouse  South     10         18  2026-01-06
2     1003  Keyboard  North      5         42  2026-01-07
3     1004   Monitor   West      3        210  2026-01-08
4     1005     Mouse   East      8         18  2026-01-09

Pandas normally treats the first row as column names. It also creates a row index starting at zero. The index shown on the left is not an extra column from the CSV; it is the DataFrame's index.

Important: read_csv() returns a DataFrame. It does not automatically save changes back to the original CSV file. To write a DataFrame to a CSV file, use df.to_csv("new_file.csv", index=False).

4. File paths: current folder, absolute path and Jupyter

Read a file in the current directory

Python
df = pd.read_csv("sales.csv")

This works when Python's current working directory contains sales.csv. To see the current directory:

Python
import os
print(os.getcwd())

Use an absolute file path

An absolute path identifies the file's location explicitly. For example, on Windows:

Python
df = pd.read_csv(r"C:\Users\Student\Documents\sales.csv")

The r before the string creates a raw string, which helps avoid interpreting backslashes as escape characters. Replace the example path with the real path on your computer.

On macOS or Linux, a path might look like this:

Python
df = pd.read_csv("/home/student/data/sales.csv")

Read a file uploaded to a notebook environment

In Jupyter Notebook, Google Colab, SageMaker or another hosted notebook, the file must be uploaded or otherwise made available to that environment. A file on your personal computer is not automatically accessible to a remote notebook server.

5. Inspect the data after importing it

After loading a file, check whether the import looks correct before performing analysis.

Python
print(df.head())       # First five rows
print(df.tail(3))      # Last three rows
print(df.shape)        # Number of rows and columns
print(df.columns)      # Column names
print(df.info())       # Data types and non-null counts
print(df.describe())   # Summary statistics for numeric columns

head() and tail() are useful for a quick visual check. shape returns a tuple of the form (rows, columns). info() helps identify unexpected data types and missing values.

File has no header row

If the first line contains actual data rather than column names, set header=None. Otherwise, Pandas would mistakenly use the first data row as the column headings.

850,Laptop,North
18,Mouse,South
42,Keyboard,North
Python
df = pd.read_csv("products.csv", header=None)
print(df.head())

Pandas will assign default column labels 0, 1, and 2.

Provide your own column names

Python
df = pd.read_csv(
    "products.csv",
    header=None,
    names=["Price", "Product", "Region"]
)

If the file already has a header row and you want to supply replacement column names, you can use names=... with the appropriate header setting. Check the file structure first to avoid accidentally treating the existing header as a data row.

7. Read only selected columns with usecols

For a wide CSV file, you may need only a few columns. The usecols parameter can reduce memory use and make the imported DataFrame easier to work with.

Python
df = pd.read_csv(
    "sales.csv",
    usecols=["Product", "Region", "Units"]
)
print(df.head())

You can also select columns by their position using integer positions in usecols, but named columns are often easier to understand and maintain. The names must match the file's actual headers.

8. Read CSV files with a different delimiter

Despite the name, a file called a CSV may use a delimiter other than a comma. Some exports use semicolons or tabs.

Semicolon-separated data

Product;Region;Units
Laptop;North;2
Mouse;South;10
Python
df = pd.read_csv("sales_semicolon.csv", sep=";")

Tab-separated data

For tab-separated text, use sep="\t":

Python
df = pd.read_csv("sales.tsv", sep="\t")

If the entire line appears in a single DataFrame column, the separator is a good first thing to check.

9. Set data types and parse dates

Specify data types with dtype

Pandas infers data types from the file, but inference may not match your needs. For example, an ID such as 00125 may need to remain text so that its leading zeros are preserved.

Python
df = pd.read_csv(
    "customers.csv",
    dtype={"CustomerID": "string", "PostalCode": "string"}
)

Use numeric types for values that you intend to calculate with, and string types for identifiers or codes that should not be treated as quantities.

Parse dates with parse_dates

Dates may initially be imported as strings. Use parse_dates to request date parsing during import:

Python
df = pd.read_csv("sales.csv", parse_dates=["OrderDate"])
print(df["OrderDate"].dtype)

If your date column uses an unusual or inconsistent format, import it first and then use pd.to_datetime() with suitable options. Always inspect the parsed values to ensure day and month have not been confused.

Python
df["OrderDate"] = pd.to_datetime(df["OrderDate"], errors="coerce")

With errors="coerce", unparseable values become NaT (the missing-value marker for dates and times), so check the resulting missing values rather than silently ignoring them.

10. Handle missing values when reading a CSV

Missing data may be represented by empty cells, NA, N/A, null, or a business-specific code such as Not recorded. Pandas recognises several common missing-value markers automatically.

Choose additional missing-value markers

Python
df = pd.read_csv(
    "survey.csv",
    na_values=["Not recorded", "unknown", "-"]
)

This tells Pandas to interpret those exact values as missing. Be careful: a marker such as - might be a legitimate value in some datasets.

Keep empty strings as ordinary values

If an empty field should not be interpreted as missing, review the keep_default_na and na_filter parameters. Their effect depends on the file and the missing-value conventions it uses. Do not change these options without inspecting representative rows.

Count missing values after import

Python
print(df.isna().sum())

For a deeper explanation of filling, removing and investigating missing data, see the Pandas missing values tutorial.

11. Handle text encoding and malformed rows

Encoding errors

If a CSV contains accented characters or text from different languages, its character encoding matters. UTF-8 is common, but files exported from older applications may use another encoding.

Python
df = pd.read_csv("customers.csv", encoding="utf-8")

If you see a decoding error, check the source application's export settings or identify the actual encoding before changing the parameter. For a known Windows-1252 file, for example, you might use encoding="cp1252". Do not guess repeatedly if the data is important.

Malformed lines

A malformed line may contain a different number of fields than expected. Recent Pandas versions provide the on_bad_lines parameter:

Python
df = pd.read_csv("sales.csv", on_bad_lines="warn")

Common choices include "error" to stop when a bad line is found, "warn" to warn and skip it, and "skip" to skip it without a warning. Skipping records can lose data, so use it only after deciding that the affected rows can be excluded.

12. Read a large CSV file in chunks

Very large CSV files may not fit comfortably in memory. The chunksize parameter returns an iterator that yields smaller DataFrame chunks.

Python
for chunk in pd.read_csv("large_sales.csv", chunksize=10000):
    print(chunk.shape)
    # Clean or analyse each chunk here

In this example, each chunk contains up to 10,000 rows. You can process a chunk, store a summary and then continue to the next one. This is useful for large files, although the best approach depends on the analysis and the available memory.

13. Important read_csv() parameters

ParameterPurposeExample
filepath_or_bufferFile name, path or supported file-like source"sales.csv"
sepField delimitersep=";"
headerRow used for column labelsheader=None
namesExplicit column labelsnames=["A", "B"]
usecolsColumns to importusecols=["Product"]
dtypeRequested data typesdtype={"ID":"string"}
parse_datesColumns to parse as datesparse_dates=["Date"]
na_valuesExtra missing-value markersna_values=["-"]
encodingText character encodingencoding="utf-8"
nrowsMaximum number of rows to readnrows=100
skiprowsRows to skip at the start or selected row positionsskiprows=2
skipinitialspaceSkip spaces after delimitersskipinitialspace=True
chunksizeRead the file in smaller batcheschunksize=10000
on_bad_linesControl handling of malformed lineson_bad_lines="warn"

Available parameters can vary by Pandas version. Consult the documentation for the version installed in your environment when using advanced options.

14. Common read_csv() errors and how to fix them

FileNotFoundError

Likely cause: the file name or path is wrong, or the file is not in the current working directory.

What to do: check os.getcwd(), confirm the exact file name and extension, and use the full path if needed.

UnicodeDecodeError

Likely cause: the file's encoding does not match the encoding Pandas is using.

What to do: check the export settings or determine the encoding and pass it using encoding=....

All data appears in one column

Likely cause: the file uses a delimiter other than a comma.

What to do: inspect the first few lines and set sep=";" or another correct separator.

Wrong column names or first record missing

Likely cause: the file does not have a header, but Pandas treated the first record as a header.

What to do: use header=None and, if appropriate, supply names=[...].

Numbers imported as text

Likely cause: values contain currency symbols, unexpected separators or other text.

What to do: inspect the affected column and clean the values before converting them. Avoid converting data blindly, because invalid entries may become missing values or cause errors.

Leading zeros disappear from codes

Likely cause: Pandas inferred a numeric type for a code such as a postal code or customer ID.

What to do: import that column as a string using dtype.

15. Practice exercises

Use the sample sales.csv file from this tutorial to practise the following tasks.

  1. Read sales.csv into a DataFrame called sales.
  2. Display the first three rows and print the DataFrame's shape.
  3. Import only the Product and Units columns.
  4. Read a semicolon-separated file called sales_eu.csv.
  5. Read customers.csv while keeping CustomerID as text.
  6. Parse the OrderDate column as dates.
  7. Read only the first 100 rows of a large CSV file.
  8. Explain how you would handle an empty cell and the text marker Not recorded.

Suggested solutions

Python
import pandas as pd

# 1. Read the file
sales = pd.read_csv("sales.csv")

# 2. Inspect rows and shape
print(sales.head(3))
print(sales.shape)

# 3. Read selected columns
small_sales = pd.read_csv("sales.csv", usecols=["Product", "Units"])

# 4. Read semicolon-separated data
eu_sales = pd.read_csv("sales_eu.csv", sep=";")

# 5. Preserve identifiers as text
customers = pd.read_csv("customers.csv", dtype={"CustomerID": "string"})

# 6. Parse a date column
sales_dates = pd.read_csv("sales.csv", parse_dates=["OrderDate"])

# 7. Read the first 100 rows
sample = pd.read_csv("large_sales.csv", nrows=100)

# 8. Treat a custom text marker as missing
survey = pd.read_csv("survey.csv", na_values=["Not recorded"])

16. Frequently asked questions

How do I read a CSV file in Pandas?

Import Pandas and call pd.read_csv("file.csv"). Make sure the file path points to a file accessible to your Python environment.

What does read_csv() return?

It returns a Pandas DataFrame by default, with rows and columns representing the imported tabular data.

How do I read a CSV file without headers?

Use pd.read_csv("file.csv", header=None). You can provide your own column labels with the names parameter.

How do I read only certain columns from a CSV?

Pass the required column names to usecols, for example pd.read_csv("sales.csv", usecols=["Product", "Units"]).

How do I read a CSV file with a semicolon separator?

Use pd.read_csv("file.csv", sep=";") to tell Pandas that semicolons separate fields.

How do I read a large CSV file?

Use chunksize to process the file in batches, or use usecols and nrows when you need only selected columns or rows.

How do I save a DataFrame as a CSV?

Use df.to_csv("output.csv", index=False) to write a DataFrame without including its index as an additional column.

What is the difference between read_csv() and read_excel()?

read_csv() imports delimited text files, while read_excel() imports spreadsheet formats such as Excel workbooks. Excel files may contain multiple sheets and formatting; CSV files contain plain tabular text.

Related Pandas Tutorials

Next: Learn how to import spreadsheet data in Pandas read_excel().



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net