1

I have a csv file deliminated by ,. The first line contains the report name, the second line contains the report data. The headers are in line 3 and all the other rows are data. How do I use the csv module to read the headers from line 3 instead of 1? Below is what I have now.

import csv
f = open ("myfile.csv", "rb")
reader = csv.reader(f, delimiter=",")
headers = reader.next()
4

3 回答 3

3

您可以使用itertools.islice从迭代器中丢弃项目。

from itertools import islice
reader = islice(csv.reader(f, delimiter=","), 2, None)
于 2013-10-29T07:31:50.820 回答
0

如果您的文件不是很大,您可以阅读所有内容并稍后丢弃前两行:

with file("myfile.csv", "rb") as f:
    reader = csv.reader(f, delimiter=',')
    lines = list(reader)[2:]
headers, value_rows = lines[0], lines[1:]
for row in value_rows:
    ...
于 2013-10-29T10:11:10.420 回答
0

也许您可以迭代直到获得所需的行:

import csv
headerLine = 3
f = open ("myfile.csv", "rb")
reader = csv.reader(f, delimiter=",")
for ii in range(0, headerLine):
    headers = reader.next()
于 2018-06-05T14:23:59.353 回答