Summary of several methods for python to write csv files

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=',')


 a_name  b_name
0       1       4
1       2       5
2       3       6
The same pandas also provides a simple way to read csv

import pandas as pd
data = pd.read_csv('test.csv')
import csv

#python2可以用file替代open
with open("test.csv","w") as csvfile: 
    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]])
index   a_name  b_name
0       1       3
1       2       3
2       3       4
Read csv file with reader
import csv
with open("test.csv","r") as csvfile:
    reader = csv.reader(csvfile)
    #这里不需要readlines
    for line in reader:
        print line

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325905457&siteId=291194637