我与python3擦肩而过(二)—— csv文件头哪去啦?

Posted on 2016-07-21 13:16  不秩稚童  阅读(5766)  评论(0编辑  收藏  举报

    在看Python Data Visualization Cookbook 这本书(基于python2),开始时读取csv文件头的时候出现问题。查了资料,又是python3的问题,从这个链接找到答案。

 

书中源码是这样的:

 

  

import csv

filename = 'ch02-data.csv'
data = []
try:
    with open(filename) as f:
        reader = csv.reader(f)
        #注意这里的缩进应该是书的印刷错误
   header = reader.next() 
   data = [row for row in reader] 
except: 
        ...略...

 

  开始在python3运行报错如下:

Traceback (most recent call last):
  File "F:\Techonolgoy\Python\file\blog\csv_open.py", line 8, in <module>
    header = reader.next()
AttributeError: '_csv.reader' object has no attribute 'next'

  查资料发现在python3里面,reader已经没有了next属性。python3中用力如下:

import csv
with open('stocks.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        # Process row
        ...

  上文提到过,这里书的缩进在印刷上可能有问题(header和data语句应该在with语句块里面)。我按照原缩进,在python2和3两种环境下测试的时候,报同样的错如下:

Traceback (most recent call last):
  File "F:\Techonolgoy\Python\file\blog\csv_open.py", line 8, in <module>
    header = next(reader)
ValueError: I/O operation on closed file.

  于是,再次修改代码,python3版本完整代码如下(python2只需要将缩进改正即可,直接用下面的代码亦可)

import csv

filename = 'ch02-data.csv'
data = []
try:
	with open(filename) as f:
		reader = csv.reader(f)
		header = next(reader)
		data = [row for row in reader]
except csv.Error as e:
	print("Error reading CSV file at line %s: %s"%(reader.line_num, e))

if header:
	print(header)
	print("=====================")
for datarow in data:
	print(datarow)	

  成功输出结果:

['day', 'ammount']
=====================
['2013-01-24', '323']
['2013-01-25', '233']
['2013-01-26', '433']
['2013-01-27', '555']
['2013-01-28', '123']
['2013-01-29', '0']
['2013-01-30', '221']