CSV (Comma-Separated Values) is a simple and widely-used file format for storing and exchanging tabular data. Each line in a CSV file represents a row of data, with individual values separated by commas (or other delimiters). This format is easy to read and write, making it a popular choice for data exchange, data analysis, and data processing tasks.
The Structure of a CSV File
A typical CSV file consists of the following components:
- Header Row: The first row of the file, which often contains the column names or field names.
- Data Rows: The subsequent rows, each containing a set of values that correspond to the columns defined in the header row.
- Delimiters: The characters used to separate the individual values in each row. The most common delimiter is the comma (
,
), but other delimiters such as semicolons (;
), tabs (\t
), or custom characters can also be used.
Here's an example of a simple CSV file:
Name,Age,City
John Doe,35,New York
Jane Smith,28,London
Bob Johnson,42,Paris
In this example, the header row contains the column names "Name", "Age", and "City". Each subsequent row represents a data record, with the values for each column separated by commas.
Reading and Writing CSV Files in Python
Python provides built-in support for working with CSV files through the csv
module. This module offers functions and classes that make it easy to read from and write to CSV files.
To read a CSV file, you can use the csv.reader()
function:
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
To write to a CSV file, you can use the csv.writer()
function:
import csv
data = [['Name', 'Age', 'City'],
['John Doe', '35', 'New York'],
['Jane Smith', '28', 'London'],
['Bob Johnson', '42', 'Paris']]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
These examples demonstrate the basic usage of the csv
module in Python, allowing you to read from and write to CSV files with ease.