writer(csvfile, dialect='excel', **fmtparams)参数说明:
,
分隔。import csv # 操作文件对象时,需要添加newline参数逐行写入,否则会出现空行现象 with open('eggs.csv', 'w', newline='') as csvfile: # delimiter 指定分隔符,默认为逗号,这里指定为空格 # quotechar 表示引用符 # writerow 单行写入,列表格式传入数据 spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|') spamwriter.writerow(['www.lmcjl.com'] * 5 + ['how are you']) spamwriter.writerow(['hello world', 'web site', 'www.lmcjl.com'])eggs.csv 文件内容如下:
www.lmcjl.com www.lmcjl.com www.lmcjl.com www.lmcjl.com www.lmcjl.com |how are you| |hello world| |web site| www.lmcjl.com其中,quotechar 是引用符,当一段话中出现分隔符的时候,用引用符将这句话括起来,以能排除歧义。
import csv with open('aggs.csv', 'w', newline='') as f: writer = csv.writer(f) # 注意传入数据的格式为列表元组格式 writer.writerows([('hello','world'), ('I','love','you')])aggs.csv文件内容:
hello,world I,love,you
import csv with open('names.csv', 'w', newline='') as csvfile: #构建字段名称,也就是key fieldnames = ['first_name', 'last_name'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) # 写入字段名,当做表头 writer.writeheader() # 多行写入 writer.writerows([{'first_name': 'Baked', 'last_name': 'Beans'},{'first_name': 'Lovely', 'last_name': 'Spam'}]) # 单行写入 writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})name.csv 文件内容,如下所示:
first_name,last_name Baked,Beans Lovely,Spam Wonderful,Spam
csv.reader(csvfile, dialect='excel', **fmtparams)应用示例如下:
import csv with open('eggs.csv', 'r', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row))输出结果:
www.lmcjl.com, www.lmcjl.com, www.lmcjl.com, www.lmcjl.com, www.lmcjl.com, how are you hello world, web site, www.lmcjl.com
import csv with open('names.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['first_name'], row['last_name'])输出结果:
Baked Beans Lovely Spam Wonderful Spam相关推荐文档:《CSV文件读写》
本文链接:http://task.lmcjl.com/news/18099.html