环境:python 3.7.3
ch02-data.csv文件:文件内容如下:自己建立一个csv文件,copy进去即可:
"Year","Country","Sex","Display Value","Numeric" "2000","USA","Both sexes","77","77.00000" "2008","Canada","Both sexes","80","89.00000" "2019","Andorra","Female","28","45.00000" "2015","China","田心","23","23.00000" "2012","United Arab Emirates","Female","78","78.00000" "2000","Antigua and Barbuda","Male","72","68.00000" "1999","Antigua and Barbuda","Male","17","17.00000" "2016","Antigua and Barbuda","Female","22","89.00000" "2017","Australia","Male","81","81.00000"
代码:
import csv import sys filename = "ch02-data.csv" data = [] try: with open(filename,encoding='utf-8') 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) sys.exit(-1) if header: print(header) print('============================================================') for datarow in data: print(datarow)
输出结果: