CSV读取特定行

时间:2014-10-20 11:27:34

标签: python csv

我有一个包含100行的CSV文件。

如何阅读特定行?

我想读第9行或第23行等吗?

4 个答案:

答案 0 :(得分:10)

您可以使用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 :(得分:4)

您只需跳过必要的行数:

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 :(得分:3)

您可以阅读所有这些内容,然后使用普通列表查找它们。

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

如果你有一个庞大的文件,这可能会扼杀你的记忆,但如果你的文件少于10,000行,你不应该遇到任何大的减速。

答案 3 :(得分:2)

您可以这样做:

with open('raw_data.csv') as csvfile:
    readCSV = list(csv.reader(csvfile, delimiter=','))
    row_you_want = readCSV[index_of_row_you_want]