🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The csv module in Python provides functionality to read from and write to CSV (Comma-Separated Values) files. CSV files are commonly used for exchanging data between different applications. This module is part of the standard library, so no installation is required.
Table of Contents
- Introduction
- Key Classes and Functions
readerwriterDictReaderDictWriter
- Examples
- Reading a CSV File
- Writing to a CSV File
- Reading a CSV File into a Dictionary
- Writing a Dictionary to a CSV File
- Real-World Use Case
- Conclusion
- References
Introduction
The csv module provides tools for reading and writing CSV files. It supports various delimiters and quoting options, making it flexible for handling different CSV formats.
Key Classes and Functions
reader
The reader class reads from a CSV file and returns each row as a list.
import csv
with open('example.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
writer
The writer class writes data to a CSV file.
import csv
with open('example.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['Name', 'Age', 'City'])
csvwriter.writerow(['Alice', '30', 'New York'])
DictReader
The DictReader class reads from a CSV file and returns each row as a dictionary.
import csv
with open('example.csv', newline='') as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
print(row)
DictWriter
The DictWriter class writes data to a CSV file from a dictionary.
import csv
with open('example.csv', 'w', newline='') as csvfile:
fieldnames = ['Name', 'Age', 'City']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writeheader()
csvwriter.writerow({'Name': 'Alice', 'Age': '30', 'City': 'New York'})
Examples
Reading a CSV File
import csv
with open('example.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
Writing to a CSV File
import csv
data = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles']
]
with open('example.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)
Reading a CSV File into a Dictionary
import csv
with open('example.csv', newline='') as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
print(row)
Writing a Dictionary to a CSV File
import csv
data = [
{'Name': 'Alice', 'Age': '30', 'City': 'New York'},
{'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'}
]
with open('example.csv', 'w', newline='') as csvfile:
fieldnames = ['Name', 'Age', 'City']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writeheader()
csvwriter.writerows(data)
Real-World Use Case
Processing a CSV File
Suppose you have a CSV file containing customer data, and you want to filter out customers from a specific city and save the result to a new CSV file.
import csv
def filter_customers(input_file, output_file, city):
with open(input_file, newline='') as csvfile:
csvreader = csv.DictReader(csvfile)
filtered_data = [row for row in csvreader if row['City'] == city]
with open(output_file, 'w', newline='') as csvfile:
fieldnames = ['Name', 'Age', 'City']
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writeheader()
csvwriter.writerows(filtered_data)
# Example usage
filter_customers('customers.csv', 'filtered_customers.csv', 'New York')
Conclusion
The csv module in Python provides an easy and flexible way to handle CSV files. Whether you need to read, write, or process CSV data, the csv module offers the necessary tools to perform these tasks efficiently.
References
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment