#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
#结果为5列
with open('egg1.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, dialect='excel')
spamwriter.writerow(['a', '1', '1', '2', '2'])
spamwriter.writerow(['b', '3', '3', '6', '4'])
spamwriter.writerow(['c', '7', '7', '10', '4'])
spamwriter.writerow(['d', '11', '11', '11', '1'])
spamwriter.writerow(['e', '12', '12', '14', '3'])
print u'结束!'
#结果为1列
with open('egg2.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['a', '1', '1', '2', '2'])
spamwriter.writerow(['b', '3', '3', '6', '4'])
spamwriter.writerow(['c', '7', '7', '10', '4'])
spamwriter.writerow(['d', '11', '11', '11', '1'])
spamwriter.writerow(['e', '12', '12', '14', '3'])
print u'结束'
#5x5
with open('egg1.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
#5x1
with open('egg2.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
D:\Software\Python\anaconda\python.exe D:/vacation-image-search-engine/test1.py
结束!
结束
['a', '1', '1', '2', '2']
['b', '3', '3', '6', '4']
['c', '7', '7', '10', '4']
['d', '11', '11', '11', '1']
['e', '12', '12', '14', '3']
['a 1 1 2 2']
['b 3 3 6 4']
['c 7 7 10 4']
['d 11 11 11 1']
['e 12 12 14 3']
Process finished with exit code 0
csv是逗号分隔符格式 。
一般我们用的execl生成的格式是xls和xlsx 直接重命名为csv的话会报错。
解决方案:出错原因是直接是把后缀为xls的execl文件重命名为csv的 正常的要是另存为csv文件 就不会报错了。