Skip the header of a file with Python's CSV reader
2016-05-09 13:40
951 查看
SOURCE: http://evanhahn.com/python-skip-header-csv-reader/
I was choosing a new credit card and was between two options. One of them offered cash back on all purchases. The other offered
less cash back on all purchases but much more cash back on certain purchases. I wanted to know: which credit card was better based on my purchase history? Like any normal person, I exported my transactions as CSV and began to dig around with
Python.
My CSV file had a header on the first line, which was different from the rest. The file looked something like this (not my actual transactions):
I wanted to use
Python's built-in CSV reader class and skip any parsing of the header line. So I did this:
The call to
This trick helped me choose my credit card and may help you do the same with CSVs in Python!
I was choosing a new credit card and was between two options. One of them offered cash back on all purchases. The other offered
less cash back on all purchases but much more cash back on certain purchases. I wanted to know: which credit card was better based on my purchase history? Like any normal person, I exported my transactions as CSV and began to dig around with
Python.
My CSV file had a header on the first line, which was different from the rest. The file looked something like this (not my actual transactions):
Date,Description,Amount 2015-01-03,Cakes,22.55 2014-12-28,Rent,1000 2014-12-27,Candy Shop,12 ...
I wanted to use
Python's built-in CSV reader class and skip any parsing of the header line. So I did this:
with open('mycsv.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) # This skips the first row of the CSV file. # csvreader.next() also works in Python 2. next(csvreader) for row in csvreader: # do stuff with rows...
The call to
nextreads the first row and discards it. From there, we're ready to iterate through the actual data! One small caveat: I had issues in Python 3 when opening the file in binary mode (
rbinstead of
r).
This trick helped me choose my credit card and may help you do the same with CSVs in Python!
相关文章推荐
- wxPython通过py2exe编译的应用程序如何去掉黑框
- python3使用requests发闪存
- Python学习笔记:字符串(str)有关函数
- python中的闭包
- 安装过 python3.X 后,python 2.7.x 打不开 idle
- ImportError: no module named win32api
- python-百度语音识别与google语音识别测试
- 扯扯python调用rpc实现分布式系统
- Python 模版引擎
- Python正则表达式
- caffe cpu版 Anaconda3 python 接口安装
- 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
- python之PyMongo使用总结
- 百度网盘爬虫(如何爬取百度网盘)
- 将Python自带版本(2.6.6)升级到2.7.9
- Python 入门(1)
- Python2.7 + beautifulSoup 4.4.1 安装配置
- Python学习笔记:字符串(str)基本内容
- python第四讲
- python基础set