How to Sort by Column in a file using Python?

How to Sort by Column in a file using Python?

To sort by a column in a file using Python, you typically would:

  1. Read the file into a list or another suitable data structure.
  2. Use Python's built-in sorting functionality to sort the list based on the desired column.
  3. Write the sorted list back to the file.

Here's a step-by-step example to sort a CSV file based on a specific column:

Example: Sorting a CSV File Based on a Column

Suppose you have a CSV file data.csv with the following content:

Name,Age,Salary Alice,28,55000 Bob,25,50000 Charlie,30,60000 

You want to sort this file based on the Age column.

import csv # 1. Read the file into a list. with open('data.csv', 'r') as file: reader = csv.reader(file) header = next(reader) # Extract the header rows = list(reader) # 2. Sort the list based on the 'Age' column (which is index 1). sorted_rows = sorted(rows, key=lambda x: int(x[1])) # 3. Write the sorted list back to the file. with open('data_sorted.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(header) # Write the header first writer.writerows(sorted_rows) # Write the sorted data 

After running the script, you'll get a data_sorted.csv file with content:

Name,Age,Salary Bob,25,50000 Alice,28,55000 Charlie,30,60000 

If you want to sort by another column or in descending order, adjust the key function in the sorted call or add the reverse=True argument to sorted.


More Tags

shopify linked-list fileoutputstream blocking create-table azure-storage-files asynchronous android-image vb.net field-description

More Programming Guides

Other Guides

More Programming Examples