2015-06-21 79 views
4

CSV文件与Python我们可以按行通过行或行读取的所有文件中的行,我想没有阅读完所有的文件和所有来读取特定行(第24号为例)线。读取CSV文件中的特定行,蟒蛇

+0

可能重复http://stackoverflow.com /问题/ 11618207 /启动读取与写入上特定线路上的CSV用的Python) – GhitaB

回答

6

您可以使用linecache.getline

linecache.getline(文件名,LINENO [,module_globals])

获取线LINENO从命名文件名的文件。这个函数永远不会引发异常 - 它会在错误时返回''(终止的换行符将包含在找到的行中)。

import linecache 


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

,或是使用itertools的consume recipe移动指针:

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) 
的[开始阅读和对与Python CSV特定行写(
+0

我不知道'open'返回迭代... – xtofl

+0

@xtofl,一个文件对象是它自己的迭代器,当你为'f:...'中的行输入时,接下来会反复调用 –

+1

并开始读取as而不是从一开始?它workwith只需消耗(F,X)和每次(初始化所需位的X)X递增,感谢您有用的答案:) – user3967257