0
0
Pandasdata~5 mins

Reading CSV files with read_csv in Pandas

Choose your learning style9 modes available
Introduction

We use read_csv to open and read data stored in CSV files. This helps us work with data easily in Python.

You have a spreadsheet saved as a CSV file and want to analyze it.
You receive data exports from websites or databases in CSV format.
You want to load sample data for practice or learning.
You need to quickly check the contents of a CSV file in Python.
You want to combine data from multiple CSV files for analysis.
Syntax
Pandas
pandas.read_csv(filepath_or_buffer, sep=',', header='infer', names=None, index_col=None, usecols=None, dtype=None, engine=None, nrows=None, skiprows=None, na_values=None, parse_dates=False, ...)

filepath_or_buffer is the path to your CSV file.

You can customize how the file is read using options like sep for separator or header for column names.

Examples
Reads a CSV file named data.csv with default settings.
Pandas
import pandas as pd
df = pd.read_csv('data.csv')
Reads a CSV file where columns are separated by semicolons instead of commas.
Pandas
df = pd.read_csv('data.csv', sep=';')
Reads a CSV without headers and assigns custom column names.
Pandas
df = pd.read_csv('data.csv', header=None, names=['A', 'B', 'C'])
Reads only columns 'A' and 'C' from the CSV file.
Pandas
df = pd.read_csv('data.csv', usecols=['A', 'C'])
Sample Program

This program creates a small CSV file, reads it using read_csv, and prints the data as a table.

Pandas
import pandas as pd

# Create a sample CSV file
csv_content = '''Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago'''
with open('sample.csv', 'w') as f:
    f.write(csv_content)

# Read the CSV file
df = pd.read_csv('sample.csv')

# Show the data
print(df)
OutputSuccess
Important Notes

If your CSV file is large, you can read only a few rows using the nrows option.

Use parse_dates=True to automatically convert date columns to date objects.

Always check the first few rows with df.head() to make sure data loaded correctly.

Summary

read_csv loads CSV files into pandas DataFrames for easy data work.

You can customize reading with options like separator, headers, and columns.

Always verify your data after loading to avoid surprises.