Python对csv排序

 

#/usr/bin/evn python
# -*- coding: utf-8 -*-
import sys
from operator import itemgetter

# input_file = open(sys.argv[1])
input_file = open("D:\\tmp\\a.csv")
output_file = open("D:\\tmp\\asorted.csv","w")

table = []

for line in input_file:
    col = line.split('|') 
    col[0] = col[0].strip()
    col[1] = int(col[1])
    col[2] = int(col[2]) 
    col[3] = int(col[3].strip())
    table.append(col) #嵌套列表table[[8,8][*,*],...]

table_sorted = sorted(table, key=itemgetter(1,2),reverse=True)#先后按列索引1,2排序,降序排列

output_file.write('header' + '\n')
for row in table_sorted:                    #遍历读取排序后的嵌套列表
    row = [str(x) for x in row]             #转换为字符串格式,好写入文本
    output_file.write("\t".join(row) + '\n')
    

input_file.close()
output_file.close()

 

你可能感兴趣的:(Python对csv排序)