Introduction
CSV (Comma-Separated Values) files are a common format for storing tabular data. They are simple text files where each line represents a row, and columns are separated by commas. Python provides several ways to work with CSV files, making it easy to read from and write to these files.
Key Concepts
-
CSV File Structure:
- Each line in a CSV file corresponds to a row in the table.
- Columns are separated by commas.
- The first row often contains headers (column names).
-
Python CSV Module:
- The
csv
module in Python provides functionality to both read from and write to CSV files. - Key classes and functions include
csv.reader
,csv.writer
,csv.DictReader
, andcsv.DictWriter
.
- The
Reading CSV Files
Using csv.reader
The csv.reader
class allows you to read CSV files row by row.
import csv with open('example.csv', mode='r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row)
Explanation:
open('example.csv', mode='r')
: Opens the file in read mode.csv.reader(file)
: Creates a CSV reader object.for row in csv_reader
: Iterates over each row in the CSV file.print(row)
: Prints each row.
Using csv.DictReader
The csv.DictReader
class reads each row into a dictionary, using the first row as the keys.
import csv with open('example.csv', mode='r') as file: csv_reader = csv.DictReader(file) for row in csv_reader: print(row)
Explanation:
csv.DictReader(file)
: Creates a CSV reader object that maps the information in each row to a dictionary using the headers as keys.
Writing CSV Files
Using csv.writer
The csv.writer
class allows you to write data to a CSV file row by row.
import csv data = [ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'], ['Charlie', 35, 'Chicago'] ] with open('output.csv', mode='w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(data)
Explanation:
open('output.csv', mode='w', newline='')
: Opens the file in write mode.csv.writer(file)
: Creates a CSV writer object.csv_writer.writerows(data)
: Writes multiple rows to the CSV file.
Using csv.DictWriter
The csv.DictWriter
class writes dictionaries to a CSV file, using the dictionary keys as column headers.
import csv data = [ {'Name': 'Alice', 'Age': 30, 'City': 'New York'}, {'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'}, {'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'} ] with open('output.csv', mode='w', newline='') as file: fieldnames = ['Name', 'Age', 'City'] csv_writer = csv.DictWriter(file, fieldnames=fieldnames) csv_writer.writeheader() csv_writer.writerows(data)
Explanation:
csv.DictWriter(file, fieldnames=fieldnames)
: Creates a CSV writer object that uses the specified fieldnames as headers.csv_writer.writeheader()
: Writes the header row to the CSV file.csv_writer.writerows(data)
: Writes multiple rows to the CSV file.
Practical Exercises
Exercise 1: Reading a CSV File
Task: Write a Python script to read a CSV file named students.csv
and print each row.
Solution:
import csv with open('students.csv', mode='r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row)
Exercise 2: Writing to a CSV File
Task: Write a Python script to write the following data to a CSV file named employees.csv
:
Name | Age | Department |
---|---|---|
John | 28 | HR |
Jane | 32 | IT |
Mike | 40 | Finance |
Solution:
import csv data = [ ['Name', 'Age', 'Department'], ['John', 28, 'HR'], ['Jane', 32, 'IT'], ['Mike', 40, 'Finance'] ] with open('employees.csv', mode='w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(data)
Exercise 3: Using csv.DictReader
and csv.DictWriter
Task: Write a Python script to read a CSV file named products.csv
and write its content to another CSV file named products_copy.csv
using csv.DictReader
and csv.DictWriter
.
Solution:
import csv with open('products.csv', mode='r') as infile, open('products_copy.csv', mode='w', newline='') as outfile: csv_reader = csv.DictReader(infile) fieldnames = csv_reader.fieldnames csv_writer = csv.DictWriter(outfile, fieldnames=fieldnames) csv_writer.writeheader() for row in csv_reader: csv_writer.writerow(row)
Common Mistakes and Tips
- File Modes: Ensure you open the file in the correct mode (
'r'
for reading,'w'
for writing). - Newline Parameter: When writing CSV files, use
newline=''
to prevent extra blank lines. - Header Row: When using
csv.DictReader
orcsv.DictWriter
, ensure the header row is correctly handled.
Conclusion
In this section, you learned how to work with CSV files in Python using the csv
module. You can now read from and write to CSV files using both csv.reader
/csv.writer
and csv.DictReader
/csv.DictWriter
. These skills are essential for handling tabular data in many real-world applications. Next, we will explore JSON data handling, which is another common format for data interchange.
Python Programming Course
Module 1: Introduction to Python
- Introduction to Python
- Setting Up the Development Environment
- Python Syntax and Basic Data Types
- Variables and Constants
- Basic Input and Output
Module 2: Control Structures
Module 3: Functions and Modules
- Defining Functions
- Function Arguments
- Lambda Functions
- Modules and Packages
- Standard Library Overview
Module 4: Data Structures
Module 5: Object-Oriented Programming
Module 6: File Handling
Module 7: Error Handling and Exceptions
Module 8: Advanced Topics
- Decorators
- Generators
- Context Managers
- Concurrency: Threads and Processes
- Asyncio for Asynchronous Programming
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with unittest
- Test-Driven Development
- Debugging Techniques
- Using pdb for Debugging
Module 10: Web Development with Python
- Introduction to Web Development
- Flask Framework Basics
- Building REST APIs with Flask
- Introduction to Django
- Building Web Applications with Django
Module 11: Data Science with Python
- Introduction to Data Science
- NumPy for Numerical Computing
- Pandas for Data Manipulation
- Matplotlib for Data Visualization
- Introduction to Machine Learning with scikit-learn