Python对csv排序

最后都变了- 提交于 2019-12-04 13:32:12

 

#/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()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!