标签:csv python dictreader dictwriter
csv模块方法
csv.reader
import csv with open(‘temp.csv‘,‘rb‘) as f: reader = csv.reader(f) for row in reader: print row
csv.writer
import csv with open(‘temp.csv‘,‘wb‘) as f: writer = csv.writer(f) writer.writerow([‘a‘,‘b‘,‘c‘]) writer.writerow([‘d‘,‘e‘,‘f‘])
csv模块类
csv.DictReader
import csv with open(‘temp.csv‘) as f: reader = csv.DictReader(f) for row in reader print(row[‘first_name‘],row[‘last_name‘])
csv.DictWriter
import csv with open(‘temp.csv‘,‘w‘) as f: fieldnames = [‘first_name‘,‘last_name‘] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerow({‘first_name‘:‘ryan‘, ‘last_name‘:‘xu‘}) writer.writerow({‘first_name‘:‘koko‘, ‘last_name‘:‘xu‘})
csv模块异常
csv.Error
import csv, sys filename = ‘some.csv‘ with open(filename, ‘rb‘) as f: reader = csv.reader(f) try: for row in reader: print row except csv.Error as e: sys.exit(‘file %s, line %d: %s‘ % (filename, reader.line_num, e))
读对象(DictReader实例和reader()函数返回的对象)公共方法
csvreader.next() csvreader.line_num csvreader.fieldnames
写对象(DictWriter实例和writer()函数返回的对象)公共方法
csvwriter.writerow(row) csvwriter.writerows(rows) csvwriter.writeheader()
本文出自 “SQL Server Deep Dives” 博客,请务必保留此出处http://ultrasql.blog.51cto.com/9591438/1704615
标签:csv python dictreader dictwriter
原文地址:http://ultrasql.blog.51cto.com/9591438/1704615