python csv在文件中查找文本,然后查找特定列

时间:2011-12-15 12:45:14

标签: python

我有一个类似

的csv数据库
apple,10,red,date
orange,12,yellow,date
pear,13,green,date
pineapple,14,brown,date

我想首先搜索例如:菠萝然后获取第三列“从中,我需要一些想法,我正在使用python csv模块

我能够

#!/usr/bin/env python


import csv
import sys

file = open("/tmp/database.txt", 'rt')
reader = csv.reader(file)
for i in reader:
   print i

输出:

['apple', '10', 'red', 'date']
['orange', '12', 'yellow', 'date']
['pear', '13', 'green', 'date']
['pineapple', '14', 'brown', 'date']

1 个答案:

答案 0 :(得分:6)

您可以检查该行的第一个元素是菠萝。获得所有第三个值的一种巧妙方法是使用list comprehension

import csv
with open("/tmp/database.txt", 'r') as file:
  reader = csv.reader(file)
  third_where_pineapple = [line[2] for line in reader if line[0] == 'pineapple']
  print (third_where_pineapple)
相关问题