2014-10-20 147 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])