在CSV
使用python的文件中,我们可以逐行或逐行读取所有文件,我想读取特定的行(第24行示例),而无需读取所有文件和所有行。
您可以使用linecache.getline:
linecache.getline(filename,lineno [,module_globals])
从名为filename的文件获取lineno。此函数将永远不会引发异常-它将在错误时返回''(找到的行将包含终止的换行符)。
import linecache
line = linecache.getline("foo.csv",24)
或者使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句