在看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']