CSV读取特定行

blu*_*inc 12 python csv

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

如何阅读特定行?

我想看看第9行还是第23行等?

Ala*_*ith 13

用于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])
Run Code Online (Sandbox Code Playgroud)


ch3*_*3ka 11

您可以使用a 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
Run Code Online (Sandbox Code Playgroud)

  • 这是否会在创建“有趣的行”时占用内存中不需要的行? (4认同)
  • 如何读取一行。以下输入是`interestingrows=[row for idx, row in enumerate(myreader) if idx in (28)] TypeError: argument of type 'int' is not iterable` (2认同)

Tim*_*ker 5

您只需跳过必要的行数:

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
Run Code Online (Sandbox Code Playgroud)


Mal*_*och 5

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

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

如果您有一个大文件,这可能会耗尽您的内存,但如果文件少于 10,000 行,您就不应该遇到任何大的减速。