[英]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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.