阅读量:0
在Python中,我们可以使用csv
模块来读取和写入CSV文件,然后利用内置的sorted()
函数对CSV文件中的数据进行排序。以下是一个简单的示例代码,演示如何对CSV文件中的数据进行排序:
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文件。')
在上面的示例中,我们首先使用csv.reader()
方法读取CSV文件中的数据,并将其保存在一个列表中。然后,我们使用sorted()
函数对该列表中的数据进行排序,通过指定key
参数来指定排序的列。最后,我们使用csv.writer()
方法将排序后的数据写入到一个新的CSV文件中。