【发布时间】:2015-06-09 00:09:02
【问题描述】:
我需要找到从第 4 列到 CSV 文件末尾的第三行。我该怎么做?我知道我可以从第 4 列中找到值 行[3] 但是我如何获得具体的第三行?
【问题讨论】:
我需要找到从第 4 列到 CSV 文件末尾的第三行。我该怎么做?我知道我可以从第 4 列中找到值 行[3] 但是我如何获得具体的第三行?
【问题讨论】:
您可以将 csv 阅读器对象转换为列表列表...行存储在列表中,其中包含列列表。
所以:
csvr = csv.reader(file)
csvr = list(csvr)
csvr[2] # The 3rd row
csvr[2][3] # The 4th column on the 3rd row.
csvr[-4][-3]# The 3rd column from the right on the 4th row from the end
【讨论】:
您可以使用itertools.islice 提取您想要的数据行,然后对其进行索引。
请注意,行和列从零开始编号,而不是从一开始。
import csv
from itertools import islice
def get_row_col(csv_filename, row, col):
with open(csv_filename, 'rb') as f:
return next(islice(csv.reader(f), row, row+1))[col]
【讨论】:
你可以保留一个计数器来计算行数:
counter = 1
for row in reader:
if counter == 3:
print('Interested in third row')
counter += 1
【讨论】:
这是一个非常基本的代码,可以完成这项工作,您可以轻松地从中创建一个函数。
import csv
target_row = 3
target_col = 4
with open('yourfile.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
n = 0
for row in reader:
if row == target_row:
data = row.split()[target_col]
break
print data
【讨论】: