美文网首页
python操作csv文件实现对特定列排序

python操作csv文件实现对特定列排序

作者: 顾子豪 | 来源:发表于2020-11-01 05:22 被阅读0次
    from operator import itemgetter # 导入定位的头方便定位按照哪里排序
    import csv
    
    if __name__ == '__main__':
        datas = [] # 开个列表存放排序过的数据
        with open('./ss.csv','r') as f:
            table=[]
            for line in f:
                col = line.split(',')
                col[0] = int(col[0])
                col[1] = col[1].strip("\n")
                table.append(col)
            table_sorted = sorted(table,key=itemgetter(0),reverse=True) #精确的按照第1列排序
            for row in table_sorted:
                datas.append(row)
        f.close()
    
        with open("answer.csv","w", newline='') as csvfile:
            writer = csv.writer(csvfile)
            for data in datas:
                writer.writerow(data)
        csvfile.close()
    
    

    待排序的文件:ss.csv

    ss.csv

    排序过的文件:answer.csv

    answer.csv

    相关文章

      网友评论

          本文标题:python操作csv文件实现对特定列排序

          本文链接:https://www.haomeiwen.com/subject/vgqyvktx.html