How to Read CSV File in Python: A Beginner’s Guide with Examples

CSV files are everywhere. From sales reports and contact lists to machine learning datasets—Comma-Separated Values (CSV) format is one of the simplest and most widely used file formats for data exchange.

If you're learning Python, knowing how to read a CSV file in Python is essential. Whether you’re a student, data analyst, or developer, this skill opens doors to real-world data handling.

How to Read CSV File in Python

In this blog, we’ll walk you through:

  • 1. What a CSV file is
     
  • 2. Different ways to read CSV files in Python
     
  • 3. Hands-on examples using csv and pandas modules
     
  • 4. Best practices and common errors
     
  • 5. Where to go next (hint: Uncodemy can help)
  •  

What Is a CSV File?

CSV stands for Comma-Separated Values. It’s a plain text file where each line represents a data record, and each value is separated by a comma.

Sample CSV content:

pgsql

CopyEdit

Copy Code

Name,Age,City

Ankit,25,Delhi

Priya,30,Mumbai

John,28,Bangalore

Here, the first line is the header, and the following lines are the data rows.

Method 1: Reading CSV Using Python's csv Module

Python has a built-in module called csv to work with CSV files.

📘 Basic Example

python

CopyEdit

import csv

with open('people.csv', mode='r') as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

✅ Output:

css

CopyEdit

Copy Code

['Name', 'Age', 'City']

['Ankit', '25', 'Delhi']

['Priya', '30', 'Mumbai']

['John', '28', 'Bangalore']

🔍 Explanation:

  • open() is used to open the file in read mode ('r')
     
  • csv.reader() parses the file into a list of rows
     
  • for row in reader: lets us loop through each record
     

Method 2: Using csv.DictReader() for Better Readability

If you prefer to work with column names, DictReader is your friend.

python

CopyEdit

import csv

with open('people.csv', mode='r') as file:

    reader = csv.DictReader(file)

    for row in reader:

        print(row['Name'], row['Age'], row['City'])

✅ Output:

nginx

CopyEdit

Copy Code

Ankit 25 Delhi

Priya 30 Mumbai

John 28 Bangalore

This method treats the first row as a header and returns each row as a dictionary, making it easy to access fields by name.

Method 3: Reading CSV Using pandas (Recommended for Data Analysis)

The pandas library is a powerful tool for data manipulation and analysis. It makes reading CSV files a breeze.

🚀 Example:

python

CopyEdit

import pandas as pd

df = pd.read_csv('people.csv')

print(df)

✅ Output:

markdown

CopyEdit

Copy Code

Name  Age      City

0  Ankit   25     Delhi

1  Priya   30    Mumbai

2   John   28  Bangalore

🌟 Advantages of Using pandas:

  • 1. Automatically reads headers
     
  • 2. Handles missing data
     
  • 3. Supports filtering, sorting, and advanced operations
     
  • 4. Ideal for data science and machine learning

Reading CSV from a URL (Online File)

With pandas, you can even read a CSV file from the internet:

python

CopyEdit

import pandas as pd

Copy Code

url = 'https://people.sc.fsu.edu/~jburkardt/data/csv/airtravel.csv'

df = pd.read_csv(url)

print(df.head())

This is great when working with open datasets or APIs.

Reading CSV with a Custom Delimiter

Sometimes, the values are separated by a character other than a comma, like a semicolon (;) or tab (\t).

python

CopyEdit

Copy Code

import pandas as pd

df = pd.read_csv('data_semicolon.csv', delimiter=';')

print(df)

This tells Python what to use as the separator between values.

Handling Encoding Errors

If you encounter errors like:

vbnet

CopyEdit

UnicodeDecodeError: 'utf-8' codec can't decode byte

Try specifying the encoding:

python

CopyEdit

df = pd.read_csv('file.csv', encoding='ISO-8859-1')

Common encodings: utf-8, ISO-8859-1, latin1

Writing CSV Files in Python (Bonus)

Once you know how to read a CSV, you’ll also want to write one!

python

CopyEdit

import csv

Copy Code

data = [['Name', 'Age'], ['Ravi', 22], ['Kiran', 24]]

with open('output.csv', mode='w', newline='') as file:

    writer = csv.writer(file)

    writer.writerows(data)

This will create a new file named output.csv with your data.

Common Errors and Fixes

Error MessageCauseSolution
FileNotFoundErrorFile path is incorrect or missingDouble-check file location
UnicodeDecodeErrorWrong encodingUse encoding='latin1' or similar
ParserError in pandasMalformed fileCheck file content & separator
All data in one column (in pandas)Wrong delimiterUse delimiter or sep parameter

Best Practices

✅ Always close the file or use with open() (auto-closes it)
✅ Use csv.DictReader for field-level access
✅ Use pandas if working with large or complex datasets
✅ Always check file encoding when reading from unknown sources
✅ Validate your CSV structure before processing

Real-World Applications of Reading CSV

Use CaseApplication
Data Science & MLLoad datasets for training/testing
Financial AnalysisRead stock market or sales reports
Web ScrapingStore scraped data in CSV format
Reporting ToolsGenerate CSV reports from applications
Contact ManagementExport/import contacts

Learn Python Data Handling with Uncodemy

If you're excited to explore data science, automation, or software development, mastering file handling and CSV in Python is just the beginning.

Take the next step by joining Uncodemy’s Python Programming Course in Noida.

📚 Course Highlights:

✅ Python from basics to advanced
✅ File handling, APIs, CSV, JSON, web scraping
✅ Assignments, projects, and interview prep
✅ Certificate + placement support
✅ Suitable for students, working professionals, and beginners

Summary: Key Takeaways

  • 1. CSV stands for Comma-Separated Values and is widely used for data storage.
     
  • 2. You can read CSV in Python using:
     
    • a. csv.reader() – basic
       
    • b. csv.DictReader() – dictionary-based
       
    • c. pandas.read_csv() – best for data analysis
       
  • 3. Handle custom delimiters, encodings, and errors like a pro
     
  • 4. Practice reading and writing CSVs for hands-on learning
     

Final Thoughts

Understanding how to read CSV file in Python equips you to handle real-world data with ease. Whether you’re building a chatbot, a dashboard, or a data science model, knowing how to read, manipulate, and analyze CSV data is an essential skill.

So go ahead—try reading your own CSV file, play around with pandas, and start building something amazing. And if you’re ready to take your Python skills further, don’t forget to check out Uncodemy’s expert-led Python course in Noida.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses