Sorting data is always necessary while working with it. In Python, sorting data is an easy task. In this tutorial, we’ll learn how to sort a CSV file numerically in Python.
Steps to Sort a CSV File Numerically in Python:
Step 1: Create a file filename.csv and fill it with the data
Name,Age Mallory,19 Bob,27 Carol,29 Alice,34 Eve,45 Trent,62
Step 2: Importing the csv module
To read the CSV file, we need the csv module. Let’s import it.
1 |
import csv |
Step 3: Reading the CSV file
Read the CSV file using the csv.reader()
method. To do this, we need to open the CSV file first.
1 2 |
with open('filename.csv', 'r') as file: reader = csv.reader(file) |
Step 4: Sorting the CSV data
Use the sorted()
method to sort the CSV data based on the required column. In this tutorial, we are sorting the data based on the second column. Use the key
parameter to specify the sorting based on the second column of CSV data.
The header row (‘Name’ and ‘Age’) is being considered for sorting. You can skip the header row by using the next()
function after creating the reader
, otherwise it will return an error.
1 2 |
header = next(reader) sorted_csv_data = sorted(reader, key=lambda row: int(row[1])) |
Step 5: Writing the sorted data to a new CSV file
Write the sorted data to a new CSV file using the csv.writer()
method.
1 2 3 4 |
with open('sorted_filename.csv', mode='w', newline='') as sorted_file: writer = csv.writer(sorted_file) for row in sorted_csv_data: writer.writerow(row) |
Conclusion:
In this tutorial, we learned how to sort a CSV file numerically in Python. The code provided can be used to sort any CSV file based on the required column.
Here’s the full code:
1 2 3 4 5 6 7 8 9 10 11 |
import csv with open('filename.csv', 'r') as file: reader = csv.reader(file) sorted_csv_data = sorted(reader, key=lambda row: int(row[1])) with open('sorted_filename.csv', mode='w', newline='') as sorted_file: writer = csv.writer(sorted_file) for row in sorted_csv_data: writer.writerow(row) |