在CSV使用python 的文件中,我们可以逐行或逐行读取所有文件,我想读取特定行(行号24示例)而不读取所有文件和所有行.
你可以使用linecache.getline:
linecache.getline(filename,lineno [,module_globals])
从名为filename的文件中获取line lineno.此函数永远不会引发异常 - 它将在错误时返回''(终止的换行符将包含在找到的行中).
import linecache
line = linecache.getline("foo.csv",24)
Run Code Online (Sandbox Code Playgroud)
或者使用itertools中的消耗配方来移动指针:
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)
Run Code Online (Sandbox Code Playgroud)