2014-10-20 240 views
5

我有一個包含100行的CSV文件。CSV讀取特定行

如何讀取特定行?

我想讀說第9行或第23行等?

+0

你現在讀的所有行如何? – 2014-10-20 11:28:58

回答

6

你可以使用一個list comprehension到文件中篩選像這樣:

with open('file.csv') as fd: 
    reader=csv.reader(fd) 
    interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)] 
# now interestingrows contains the 28th and the 62th row after the header 
1

您簡單地跳過行的必要數量:

with open("test.csv", "rb") as infile: 
    r = csv.reader(infile): 
    for i in range(8): # count from 0 to 7 
     next(r)  # and discard the rows 
    row = next(r) # "row" contains row number 9 now 
2

你可以閱讀所有這些,然後使用普通的列表來找到它們。

with open('bigfile.csv','rb') as longishfile: 
    reader=csv.reader(longishfile) 
    rows=[r for r in reader] 
print row[9] 
print row[88] 

如果你有一個巨大的文件,這會殺了你的記憶,但如果該文件的少得了1個萬多行,你不應該遇到任何大的減速。

+2

你可以簡單的'rows = list(reader)' – 2014-10-20 11:37:19

0

使用list抓住所有的行同時作爲一個列表。然後通過列表中的索引/偏移訪問您的目標行。例如:

#!/usr/bin/env python 

import csv 

with open('source.csv') as csv_file: 
    csv_reader = csv.reader(csv_file) 
    rows = list(csv_reader) 

    print(rows[8]) 
    print(rows[22])