1、使用argparse组件,获取命令行参数;使用re组件,获取需要查找的字符串所在行
2、使用pandas组件,对文件进行排序。
3、命令行执行数据获取及排序,写入文件;
以下是完整代码:
#coding:utf-8 import re import argparse import pandas as pd parser = argparse.ArgumentParser(description='manual to this script') parser.add_argument('--ip', type=str, default = None) parser.add_argument('--type', type=str, default=None) args = parser.parse_args() filterStr = args.ip + " " + args.type f1=file('perf.csv','r') perfdata=f1.readlines() f1.close() results = [] f2 = open('filter.csv', 'w') f2.writelines(perfdata[0]) for i in perfdata: n = re.findall(filterStr, i) if n: f2.writelines(i) f2.close() df = pd.read_csv('filter.csv') df = df.sort_values('elapsed',ascending = False) df.to_csv('filterOrder.csv',index = False)
实例扩展:
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里的数据排序的具体代码的详细内容,更多关于用python给csv里的数据如何排序的资料请关注其它相关文章!
标签:
python,csv,数据排序
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com
暂无“用python给csv里的数据排序的具体代码”评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。