krisdigitx
krisdigitx

Reputation: 7126

python csv find text in file and then find a specific column

i have a database of csv something like

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

i want to first search for eg: pineapple and then get third column" from it, i need some ideas, i am using the python csv module

i am able to get

#!/usr/bin/env python


import csv
import sys

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

output:

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

Upvotes: 2

Views: 3736

Answers (1)

phihag
phihag

Reputation: 287825

You can just check whether the first element of the line is pineapple. A neat way to get all the third values is to use a 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)

Upvotes: 6

Related Questions