我有一个类似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']
最佳答案
您可以只检查该行的第一个元素是否为菠萝。获取所有第三个值的一种巧妙方法是使用 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)
关于python csv 在文件中查找文本,然后查找特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8520329/