CSV模块提供的常见函数有:
1.csv.write(csvfile, dialect='excel', **fmtparams) 返回一个writer对象。
2.csv.reader(csvfile,dialect ='excel',** fmtparams)返回一个reader对象。
3.classcsv.DictWriter(f,fieldnames,restval ='',extrasaction ='raise',dialect ='excel',* args,** kwds)
创建一个像常规编写器一样操作的对象(操作字典)。
4.classcsv.DictReader(f,fieldnames = None,restkey = None,restval = None,dialect ='excel',* args,** kwds)
创建一个像常规阅读器一样操作的对象(操作字典)。
5.csvfile.writeheader()为CSV文件添加第一行标题,只有在操作字典对象才有。
import csv
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['张三','李四'])
执行该代码效果如下
open文件的时候加newline=''是为了消除空行。官方解释如下:If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specifynewline='', since the csv module does its own (universal) newline handling.如果不带newline=‘’,你会发现也能写入结果,但是每行内容之间总是会多出一个空行。
操作字典的情况如下:
import csv
headers = ['张三', '李四']
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, headers)
writer.writeheader()
writer.writerow({'张三':17,'李四':18})
writer.writerow({'张三':19,'李四':20})
当然,你也可以遍历字典去写入:
import csv
headers = ['姓名', '语文', '数学', '英语', '理综']
data = {"张三":{"语文":119,"数学":120, "英语":121, "理综":122},\
"李四":{"语文":123,"数学":124, "英语":125, "理综":126}}
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, headers)
writer.writeheader()
for r in data:
print(r,type(r),data[r]["语文"])
writer.writerow({"姓名":r,"语文":data[r]["语文"], "数学":data[r]["数学"], "英语":data[r]["英语"],"理综":data[r]["理综"]})