2

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']

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.