python写⼊csv⽂件的⼏种⽅法总结⽣成test.csv⽂件
#coding=utf-8
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
<_csv("test.csv",index=False,sep=',')
内容为
a_name  b_name
014
125
236
读取csv⽂件
#coding=utf-8
import pandas as pd
data = pd.read_csv('test.csv')
print(data)
输出
C:\Users\macname\Desktop\t>python test.py
a_name  b_name
014
125
236
另⼀种⽅法⽤csv包,⼀⾏⼀⾏写⼊
#coding=utf-8
import csv
#python2可以⽤file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile)
#先写⼊columns_name
#写⼊多⾏⽤writerows
writer.writerows([["index","a_name","b_name"],[0,1,3],[1,2,3],[2,3,4]])
内容为
index,a_name,b_name
0,1,3
1,2,3
2,3,4
读取csv⽂件⽤
#coding=utf-8
import csv
with open("test.csv","r") as csvfile:
reader = ader(csvfile)
#这⾥不需要readlines
for line in reader:
print(line)python怎么读csv数据
输出
C:\Users\macname\Desktop\t>python test.py ['index', 'a_name', 'b_name']
[]
['0', '1', '3']
[]
['1', '2', '3']
[]
['2', '3', '4']
[]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。