Let's study Python

Working with CSV files in Python is made easy with the versatile `csv` module.

# Python CSV Usage

## Introduction
In Python, the `csv` module is used to work with CSV (Comma Separated Values) files. CSV files are commonly used for storing tabular data in a plain text format. This module provides functionality to read, write, and manipulate CSV files in Python.

## Reading CSV Files
To read data from a CSV file, you can use the `csv.reader` class. Here is an example of how to read data from a CSV file named `data.csv`:

“`python
import csv

with open(‘data.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
“`

In this code snippet, we first open the CSV file in read mode and then create a `csv.reader` object to iterate over each row in the file.

## Writing CSV Files
To write data to a CSV file, you can use the `csv.writer` class. Here is an example of how to write data to a CSV file named `output.csv`:

“`python
import csv

data = [
[‘Name’, ‘Age’, ‘Country’],
[‘Alice’, 25, ‘USA’],
[‘Bob’, 30, ‘Canada’],
[‘Charlie’, 35, ‘UK’]
]

with open(‘output.csv’, ‘w’, newline=”) as file:
writer = csv.writer(file)
writer.writerows(data)
“`

In this code snippet, we first define the data that we want to write to the CSV file as a list of lists. We then open the CSV file in write mode and create a `csv.writer` object to write the data to the file.

## Manipulating CSV Data
The `csv` module provides various functions to manipulate CSV data, such as `DictReader` and `DictWriter` classes to work with dictionaries instead of lists. Here is an example of how to read and write CSV files using dictionaries:

“`python
import csv

# Reading CSV file as dictionary
with open(‘data.csv’, ‘r’) as file:
reader = csv.DictReader(file)
for row in reader:
print(row)

# Writing CSV file from dictionary
fieldnames = [‘Name’, ‘Age’, ‘Country’]
data = [
{‘Name’: ‘Alice’, ‘Age’: 25, ‘Country’: ‘USA’},
{‘Name’: ‘Bob’, ‘Age’: 30, ‘Country’: ‘Canada’},
{‘Name’: ‘Charlie’, ‘Age’: 35, ‘Country’: ‘UK’}
]

with open(‘output.csv’, ‘w’, newline=”) as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
“`

In this code snippet, we first use `csv.DictReader` to read the CSV file as a dictionary and `csv.DictWriter` to write the data to the CSV file using dictionaries.

## Conclusion
In this guide, we have covered the basics of working with CSV files in Python using the `csv` module. By using the functionality provided by this module, you can easily read, write, and manipulate CSV data in your Python programs.