繁体   English   中英

CSV 读取特定行

[英]CSV read specific row

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

如何读取特定行?

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

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

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

您只需跳过必要的行数:

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

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

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 行,你不应该遇到任何大的减速。

你可以这样做:

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

可能这可以帮助你,使用熊猫你可以很容易地用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],:]

输出 :

输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM