Python CSV 读取特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26464567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:30:58  来源:igfitidea点击:

CSV read specific row

pythoncsv

提问by blue_zinc

I have a CSV file with 100 rows.

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

How do I read specific rows?

如何读取特定行?

I want to read say the 9th line or the 23rd line etc?

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

采纳答案by ch3ka

You could use a list comprehensionto filter the file like so:

您可以使用 alist 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

回答by Tim Pietzcker

You simply skip the necessary number of rows:

您只需跳过必要的行数:

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

回答by Malcolm Murdoch

You could read all of them and then use normal lists to find them.

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

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

If you have a massive file, this can kill your memory but if the file's got less than 10,000 lines you shouldn't run into any big slowdowns.

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

回答by Alan W. Smith

Use listto grab all the rows at once as a list. Then access your target rows by their index/offset in the list. For example:

用于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])

回答by xtiger

You can do something like this :

你可以这样做:

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