读取csv或tsv格式的文件时,经常需要读取跳过文件头,直接读取文件内容,假定我们要读取的文件格式如下:
data.tsv
id | score | review |
---|---|---|
1 | 5.0 | This is a good product |
2 | 3.0 | Not so bad |
我们只需读取文件数据而无需文件头信息,那么最简单的方法就是打开文件后在循环中判断是否为第一行,是第一行则跳过:
with open('data.tsv', 'r') as f:
lines = f.readlines()
for line_counter, line in emunerate(lines):
if line_counter != 0: # skip first line of the file
# process data
...
f.close()
但是这种写法在每次循环中都要做一次if判断,很耗时,下面给定几种更为高效的方法:
with open('data.tsv', 'r') as f:
next(f) # skip first line
lines = f.readlines()
for line in lines:
# process data
...
f.close()
如果需要文件头,则可将next函数的返回值存入变量中:
first_line = next(f)
f.readlines()函数返回的是一个保存了每行内容的list,根据此特性可以直接从第二行开始获取
with open('data.tsv', 'r') as f:
lines = f.readlines()[1:] # get [1, ...n) elements with index starts from 0
for line in lines:
# process data
...
f.close()
from itertools import islice
with open('data.tsv', 'r') as f:
for line in islice(f, 1, None):
# process data
f.close()
这个工具有个好处就是可以根据参数从任一行开始读取,例如在islice()函数的第二个参数中传入5,则表示从第5行开始读取。