2015-06-21 88 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