写CSV文件,默认是逗号分隔:
import csv
data = [
['baidu', 100, 'hust'],
['sogou', 100, 'hust'],
['google', 100, 'hust'],
]
with open('/tmp/abc.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerows(data)
也可以一行一行地写,下面的例子换成Tab分隔:
with open('/tmp/abc.csv', 'w') as f:
csv_writer = csv.writer(f, csv.excel_tab)
for i in data:
csv_writer.writerow(i)
读CSV文件:
with open('/tmp/abc.csv', 'r') as f:
for i in csv.reader(f, csv.excel_tab):
print(i)
注意读和写使用的分隔符得一致。