如何从CSV文件存储行?

时间:2015-07-21 23:55:46

标签: csv python-3.x

在我的CSV文件中,我有5行描述该文件。我需要存储第三行但忽略其余部分。我设法编写了一个忽略所有描述标题的代码但是如何只存储一行? 我写了这段代码来忽略所有描述标题

for row in range(6):
       csvfile.readline()

1 个答案:

答案 0 :(得分:0)

您可以使用itertools.islice获取第8行,它将是5个标题行之后的第3行,即第8行或第7行:

from itertools import islice

line = next(islice(csvfile, 7, 8)) # start=index 7, end= index 8 so one line 

您还可以使用linecache.getline从文件中获取一行,但效率最高。

如果你有一个非常大的文件,itertools consume recipe也可能有用,可以跳过n行:

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)