csv文件的读写
csv文件的读写
库:
import csv
读取csv
csvFile = open("instance.csv", "r")
reader = csv.reader(csvFile)
写入csv
Python 3.0 使用out = open(outfile, 'w', newline='')
Python 2.0使用out = open(outfile, 'wb')
不然有空行产生
csvFile = open("instance.csv", "wb")
writer = csv.writer(csvFile)
writer.writerow(fileHeader)
writer.writerow(d1)
writer.writerow(d1)
csvFile.close()
windows文件里面需要加\
c_w = open("D:\03_Data\00_2016-aaai\Data\biaozhu\amusement.csv", "wb")
writer = csv.writer(c_w)
writer.writerow([str(1),'D:dkel'])
writer.writerow([str(1),'D:dkel'])
writer.writerow([str(1),'D:dkel'])
c_w.close()
追加写入:
csvFile = open("instance.csv", "a")
writer = csv.writer(csvFile)
writer = csv.writer(csvFile)
使用pandas包写入
import pandas as pd
任意的多组列表 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=',')
参考:
[1] python读取CSV文件 https://www.cnblogs.com/liujinhong/p/5937527.html
[2] Python--读写CSV文档 https://blog.csdn.net/guoziqing506/article/details/52014506
[3] python写入csv文件的几种方法总结 https://blog.csdn.net/waple_0820/article/details/70049953