How To Sort A CSV File Numerically In Python

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.

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.

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.

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.

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: