CSV 读取特定行

问题描述 投票:0回答:7

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

如何读取特定行?

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

python csv
7个回答
26
投票

您可以使用

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

20
投票

使用

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

15
投票

您只需跳过必要的行数即可:

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

5
投票

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

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 行,您不应该遇到任何大的速度下降。


2
投票

你可以这样做:

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

1
投票

也许这可以帮助你,使用 pandas 你可以轻松地做到这一点

loc

'''
Reading 3rd record using pandas -> (loc)
Note : Index start from 0 
If want to read second record then 3-1 -> 2
loc[2]` -> read second row and `:` -> entire row details 
'''

import pandas as pd
df = pd.read_csv('employee_details.csv')
df.loc[[2],:]

输出:


0
投票
with open("data.csv") as data_file:
    data = csv.reader(data_file)
    temperature = []
    for row in data:
        print(row[1])

如果您处理的数据量较少,我发现这是一种更简单的方法。

© www.soinside.com 2019 - 2024. All rights reserved.