read specific line in csv file , python

最后都变了- 提交于 2019-12-19 21:27:07

问题


In an CSV file with python we can read all the file line by line or row by row , I want to read specific line (line number 24 example ) without reading all the file and all the lines.


回答1:


You can use linecache.getline:

linecache.getline(filename, lineno[, module_globals])

Get line lineno from file named filename. This function will never raise an exception — it will return '' on errors (the terminating newline character will be included for lines that are found).

import linecache


line = linecache.getline("foo.csv",24)

Or use the consume recipe from itertools to move the pointer:

import collections
from itertools import islice

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)

with open("foo.csv") as f:
    consume(f,23)
    line = next(f)


来源:https://stackoverflow.com/questions/30964244/read-specific-line-in-csv-file-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!