Sort CSV Files With Python
In Python, we can use the csv module to read and write CSV files, and then use the built-in sorted() function to sort the data in the CSV file. Here is a simple example code demonstrating how to sort the data in a CSV file.
import csv
# 读取CSV文件
with open('data.csv', 'r') as file:
reader = csv.reader(file)
data = list(reader)
# 对数据进行排序
sorted_data = sorted(data, key=lambda x: x[0]) # 根据第一列数据进行排序
# 写入排序后的数据到新的CSV文件
with open('sorted_data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(sorted_data)
print('数据已排序并写入新的CSV文件。')
In the example above, we start by using the csv.reader() method to read the data from a CSV file and save it in a list. Then, we use the sorted() function to sort the data in the list by specifying the key parameter for the column to sort by. Finally, we use the csv.writer() method to write the sorted data to a new CSV file.