csv | Python Standard Library – Real Python
The Python csv module provides functionality to read from and write to CSV (comma-separated values) files, which are a common format for data interchange.
The module offers both high-level and low-level interfaces for handling CSV data.
Here’s a quick example:
This code will work with the following people.csv file:
Key Features
- Reads CSV files into lists or dictionaries
- Writes data to CSV files from lists or dictionaries
- Supports custom delimiters and quoting characters
- Handles CSV dialects for different CSV formats
Frequently Used Classes and Functions
Examples
Writing data to a CSV file:
Common Use Cases
- Reading data from CSV files for analysis
- Writing data to CSV files for sharing or storage
- Converting between different CSV dialects
Real-World Example
You have a CSV file with employee data. You want to:
- Read the data.
- Filter out employees under age 30.
- Write the filtered list to a new CSV file.
Here’s a sample CSV file:
Below is the Python code to perform the needed operations:
The DictReader class uses the headers as keys and generates dictionaries with the values in each row. In the loop, you convert the age field into a number using int() to allow filtering and to store the data into a list.
Then, you use a comprehension to apply the filtering and finally write the resulting data to a new CSV file called filtered.csv using DictWriter.
For additional information on related topics, take a look at the following resources:
- Reading and Writing CSV Files (Course)
- Reading and Writing CSV Files in Python (Quiz)