失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python编写程序使用csv模块方法将数据以CSV格式写入文本文件

Python编写程序使用csv模块方法将数据以CSV格式写入文本文件

时间:2019-02-14 01:11:14

相关推荐

Python编写程序使用csv模块方法将数据以CSV格式写入文本文件

Python编写程序实现以下目标

( 1 ) 使用普通文件读写方法将数据以CSV格式写入文本文件,然后从文件读取数据,将数据按准考证号排序输出。

( 2 ) 使用csv模块方法将数据以CSV格式写入文本文件,然后从文件读取数据,将数据按姓名排序输出。

#(1)d=[["101704",'吴娇','女','学前教育'],["101704",'张思思','女','学前教育'],["701321",'蔡鸿宇','男','电气自动化'],["180422",'甘雨婷','女','电气自动化'],["111102",'陈鹏涛','男','电子商务'],["701220",'杜建辉','男','电子商务']]print('使用普通文件读取方法写CSV文件')f=open('d:/data7-3-1.txt','w')f.write('准考证号,姓名,性别,专业\n')for a in d:f.write(','.join(a)+'\n')f.close()print('数据已存入文件:d:/data7-3-1.txt')f=open('d:/data7-3-1.txt','r')ds=f.readlines()f.close()n=0for a in ds:ds[n]=a.split(',')n+=1def ks(a):return a[0]d0=ds[0]del ds[0]ds.sort(key=ks)xb='{1:{0}<4}{2:{0}<3}'.format(chr(12288),'姓名','性别')print('%-6s'%'准考证号',xb,'专业')for x in ds:xb='{1:{0}<4}{2:{0}<3}'.format(chr(12288),x[1],x[2])print('%-10s'%x[0],xb,x[3].strip())#(2)print('\n使用csv模块方法读写CSV文件')import csvf=open('d:/data1-2.txt','w')cw=csv.writer(f)cw.writerow(['准考证号','姓名','性别','专业'])for a in d:cw.writerow(a)f.close()print('数据已存入文件:data1-2.txt')f=open('d:/data1-2.txt','r')cr=csv.reader(f)ds=[]for r in cr:if len(r)>1:ds.append(r)def ks(a):return a[1]d0=ds[0]del ds[0]ds.sort(key=ks,reverse=True)xb='{1:{0}<4}{2:{0}<3}'.format(chr(12288),'姓名','性别')print('%-6s'%'准考证号',xb,'专业')for x in ds:xb='{1:{0}<4}{2:{0}<3}'.format(chr(12288),x[1],x[2])print('%-10s'%x[0],xb,x[3].strip())

如果觉得《Python编写程序使用csv模块方法将数据以CSV格式写入文本文件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。