for row in csv.reader(['one,two,three']):
print(row)# ['one', 'two', 'three']
3.2实例:读写
实例1.1:读取CSV文件的最简单示例:
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:print(row)
实例1.2:相应的最简单的写作示例是:
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
实例2.1:写数据
with open('test_csv_data.csv', 'w', newline='') as f:
writer = csv.writer(f, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['My name is','Tom', 'Bob', 'Jim', 'May'])
writer.writerow(['Color is', 'red', 'yellow green','blue'])
实例2.2:读数据
with open('test_csv_data.csv', newline='') as f:
spamreader = csv.reader(f, delimiter=' ', quotechar='|')
for row in spamreader:
print(', '.join(row))
# My name is, Tom, Bob, Jim, May
# Color is, red, yellow green, blue
实例3.2:写入csv文件
with open('csv_test.csv', 'w',newline='') as f:# 如不指定newline='',有时则每写入一行将有一空行被写入
writer = csv.writer(f)
writer.writerow(['name', 'age', 'tel']) # 写入一行用writerow
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='') as f:
reader = csv.reader(f, 'unixpwd')
3.6捕获和报告错误:
import csv, sys
filename = 'some.csv'
with open(filename, newline='') as f:
reader = csv.reader(f)
try:
for row in reader:
print(row)
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
3.7示例Sniffer:
with open('test_csv_data.csv', newline='') as f:
dialect = csv.Sniffer().sniff(f.read(1024))
f.seek(0)
reader = csv.reader(f, dialect,delimiter=' ',quotechar='|', quoting=csv.QUOTE_NONE,escapechar='$')
# process CSV file contents here
for i in reader:
print(i)