python读写csv文件并增加行列的实例代码
python读写csv文件并增加行列,具体代码如下所示:
#-*-coding:utf-8-*-
"""
CreatedonThuAug1711:28:172017
@author:ShawnYuen
"""
importcsv
d=list(range(38685))
withopen('./kinetics_test.csv')asf1:
f_csv=csv.DictReader(f1)
fori,rowinenumerate(f_csv):
#print(row)
key1='label'
value1='test'
row[key1]=value1
key2='is_cc'
value2='0'
row[key2]=value2
d[i]=row
f1.close()
headers=['label','youtube_id','time_start','time_end','split','is_cc']
withopen('./kinetics_test_new_.csv','w')asf:
f_csv=csv.DictWriter(f,headers)
f_csv.writeheader()
f_csv.writerows(d)
f.close()
withopen('./kinetics_test_new_.csv','rt')asfin:
lines=''
forlineinfin:
ifline!='\n':
lines+=line
withopen('./kinetics_test_new.csv','wt')asfout:
fout.write(lines)
为了下载test数据,
方法一:用Excel打开csv文件,手动添加label和is_cc;
方法二:利用python里面的csv模块改写。
生成的csv文件中奇怪的多了一些空行,然后找到解决方法,见参考资料。
python使用writerows写csv文件产生多余空行
python定义给定初值或长度的list
知识点扩展:
python写入csv文件的几种方法总结
最常用的一种方法,利用pandas包
importpandasaspd
#任意的多组列表
a=[1,2,3]
b=[4,5,6]
#字典中的key值即为csv中列名
dataframe=pd.DataFrame({'a_name':a,'b_name':b})
#将DataFrame存储为csv,index表示是否显示行名,default=True
dataframe.to_csv("test.csv",index=False,sep=',')
a_nameb_name
014
125
236
同样pandas也提供简单的读csv方法
importpandasaspd
data=pd.read_csv('test.csv')
会得到一个DataFrame类型的data,不熟悉处理方法可以参考pandas十分钟入门
另一种方法用csv包,一行一行写入
importcsv
#python2可以用file替代open
withopen("test.csv","w")ascsvfile:
writer=csv.writer(csvfile)
#先写入columns_name
writer.writerow(["index","a_name","b_name"])
#写入多行用writerows
writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
indexa_nameb_name
013
123
234
读取csv文件用reader
importcsv
withopen("test.csv","r")ascsvfile:
reader=csv.reader(csvfile)
#这里不需要readlines
forlineinreader:
printline
总结
以上所述是小编给大家介绍的python读写csv文件并增加行列的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!