Introduction
Comma-Separated Values (CSV) files are a common way to store and exchange tabular data. Python provides built-in modules to read from and write to CSV files, making it easy to work with data in this format. In this guide, we'll explore how to work with CSV files in Python, including reading, writing, and manipulating data, and provide sample code to illustrate these operations.
Reading from a CSV File
Let's explore how to read data from a CSV file with sample code:
1. Using the csv.reader
Module
import csv
# Open the CSV file
with open('data.csv', mode='r') as file:
# Create a CSV reader
csv_reader = csv.reader(file) # Iterate through the rows
for row in csv_reader:
print(row)
2. Using pandas
Library
import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv('data.csv')
Writing to a CSV File
Let's explore how to write data to a CSV file with sample code:
1. Using the csv.writer
Module
import csv
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
# Open the CSV file for writing
with open('data.csv', mode='w', newline='') as file:
# Create a CSV writer
csv_writer = csv.writer(file) # Write data to the file
for row in data:
csv_writer.writerow(row)
2. Using pandas
Library
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
# Create a DataFrame
df = pd.DataFrame(data)
# Write the DataFrame to a CSV file
df.to_csv('data.csv', index=False)
Working with CSV Data
Python provides various tools to manipulate and process data from CSV files, including sorting, filtering, and data analysis using libraries like pandas
.
Conclusion
Working with CSV files is a common task in data-related Python projects. By mastering the techniques of reading, writing, and processing data in this format, you can efficiently manage and analyze tabular data for various applications.