Python Tutorial — Learn Python Step by Step
Key takeaway: Master Python programming from scratch — variables, loops, functions, OOP, file handling, and libraries — with clear human-readable explanations and runnable code examples.
Reading CSV Files in Python
Python's csv module provides two main approaches for reading CSV files: csv.reader (list-based) and csv.DictReader (dictionary-based). Both handle quoting, escaping, and delimiters automatically.
Basic Reading with csv.reader
import csv
# csv.reader returns each row as a list of strings
with open("employees.csv", "r") as f:
reader = csv.reader(f)
# First row is usually the header
header = next(reader)
print(header) # ["name", "department", "salary"]
# Iterate remaining rows
for row in reader:
name, department, salary = row
print(f"{name} works in {department}, earns ${salary}")
# Output:
# Alice works in Engineering, earns $95000
# Bob works in Marketing, earns $72000Reading with csv.DictReader
import csv
# DictReader uses the first row as keys automatically
with open("employees.csv", "r") as f:
reader = csv.DictReader(f)
# Access columns by header name — much more readable
for row in reader:
print(f"{row[\"name\"]}: {row[\"department\"]} - ${row[\"salary\"]}")
# reader.fieldnames gives you the header list
# print(reader.fieldnames) # ["name", "department", "salary"]
# If CSV has no header, provide field names manually
with open("no_header.csv", "r") as f:
reader = csv.DictReader(f, fieldnames=["id", "name", "email"])
for row in reader:
print(row["email"])Reading with Different Delimiters
import csv
# Tab-separated values (TSV)
with open("data.tsv", "r") as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
print(row)
# Semicolon-separated (common in European locales)
with open("data_eu.csv", "r") as f:
reader = csv.reader(f, delimiter=";")
for row in reader:
print(row)
# Pipe-separated
with open("data.txt", "r") as f:
reader = csv.reader(f, delimiter="|")
for row in reader:
print(row)
# Auto-detect delimiter with csv.Sniffer
with open("unknown.csv", "r") as f:
sample = f.read(1024)
dialect = csv.Sniffer().sniff(sample)
f.seek(0)
reader = csv.reader(f, dialect)
for row in reader:
print(row)Loading CSV into Data Structures
import csv
# Load all rows into a list of dictionaries
def load_csv(filename):
with open(filename, "r") as f:
return list(csv.DictReader(f))
people = load_csv("employees.csv")
print(f"Total records: {len(people)}")
print(people[0]) # {"name": "Alice", "department": "Engineering", ...}
# Filter while reading
def load_filtered(filename, department):
results = []
with open(filename, "r") as f:
for row in csv.DictReader(f):
if row["department"] == department:
results.append(row)
return results
engineers = load_filtered("employees.csv", "Engineering")
# Convert types during reading (CSV values are always strings)
with open("sales.csv") as f:
reader = csv.DictReader(f)
total = 0
for row in reader:
amount = float(row["amount"]) # convert string to float
quantity = int(row["quantity"])
total += amount * quantity
print(f"Total revenue: ${total:,.2f}")Handling Encoding and Errors
import csv
# Handle UTF-8 BOM (common in Excel exports)
with open("excel_export.csv", "r", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
# Handle encoding errors gracefully
with open("messy.csv", "r", encoding="utf-8", errors="replace") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Skip malformed rows
with open("dirty.csv", "r") as f:
reader = csv.reader(f)
for i, row in enumerate(reader, 1):
try:
if len(row) < 3: # expected 3 columns
print(f"Skipping row {i}: too few columns")
continue
process(row)
except Exception as e:
print(f"Error on row {i}: {e}")- Use
csv.DictReaderfor readable, header-based column access. - All CSV values are strings — cast to
int/floatas needed. - Use
encoding="utf-8-sig"for Excel-exported CSV files with BOM. - Use
csv.Snifferto auto-detect delimiters in unknown files. - Process row-by-row for large files to avoid loading everything into memory.
Python Programming Tutorial — Learn Python in a practical, step-by-step way. According to the official Python documentation, Python emphasizes code readability and simplicity, making it ideal for beginners.
Related tools: Python Online Compiler | Python Examples | JavaScript Tutorial | Java Tutorial
Python Career & Learning Guide
Python is the world's most popular programming language for beginners, data science, AI/ML, web development, and automation. This tutorial teaches Python step-by-step with clear explanations and runnable code examples in our free Python Compiler.
Why Learn Python in 2026?
- #1 Most Popular Language: Ranked first on TIOBE, Stack Overflow, and GitHub.
- AI and Data Science: The primary language for machine learning (TensorFlow, PyTorch, scikit-learn) and data analysis (Pandas, NumPy).
- Web Development: Django and Flask power scalable backends at companies like Instagram and Spotify.
- Automation & Scripting: Automate files, emails, web scraping, and data processing in minutes.
Python vs Other Languages
| Feature | Python | Java | JavaScript | C++ |
|---|---|---|---|---|
| Syntax | Very clean, readable | Verbose | Moderate | Complex |
| Typing | Dynamic, strong | Static, strong | Dynamic, weak | Static, strong |
| Best For | AI/ML, Data, Web | Enterprise, Android | Web Frontend/Backend | Systems, Games |
| Learning Time | 2–4 weeks basics | 4–6 weeks basics | 3–4 weeks basics | 8–12 weeks basics |
Frequently Asked Questions
Do I need prior programming experience to learn Python?
No! Python is specifically designed to be beginner-friendly. This tutorial starts from zero and builds up gradually.
Which Python version should I use?
Python 3.10+ is recommended. All examples in this tutorial use Python 3 syntax.
Is this Python tutorial completely free?
Yes, 100% free with no registration or sign-up required. Access all lessons and code examples anytime.