从CSV中读取特定行
我有一个包含100行的CSV文件。
我该怎么读取特定的行呢?
比如,我想读取第9行或者第23行等等?
7 个回答
2
你可以这样做:
with open('raw_data.csv') as csvfile:
readCSV = list(csv.reader(csvfile, delimiter=','))
row_you_want = readCSV[index_of_row_you_want]
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行,通常不会出现太大的速度问题。
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
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])
26
你可以用一种叫做 列表推导式
的方法来筛选文件,像这样:
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