2014-10-04 149 views
0

我有一個十行CSV文件。從這個文件中,我只想要第四行。什麼是最快的方法來做到這一點?我在尋找類似:使用Python打印CSV文件中的特定行

with open(file, 'r') as my_file: 
    reader = csv.reader(my_file) 
    print reader[3] 

其中reader[3]顯然是不正確的語法我想要實現的。我如何將讀者移到第4行並獲取它的內容?謝謝!

回答

2

如果你只有10行,你可以將整個文件加載到一個列表:

with open(file, 'r') as my_file: 
    reader = csv.reader(my_file) 
    rows = list(reader) 
    print rows[3] 

對於較大的文件,使用itertools.islice()

from itertools import islice 

with open(file, 'r') as my_file: 
    reader = csv.reader(my_file) 
    print next(islice(reader, 3, 4)) 
+0

完美,正是我一直在尋找爲:)該文件大約120行,永遠不會超過。我認爲列表就足夠了。謝謝! – mart1n 2014-10-04 21:12:27