有条件地提取CSV文件行?

时间:2016-08-12 11:47:49

标签: python csv

我有一个如下所示的CSV文件:

Germany,1928,Food
Iceland,1943,Oil
France,1923,Plastics
Russia,1901,Steal
South Africa,1932,Silver
Russia,1905,Gold
Brazil,1901,Platinum

我想让它搜索第一列,如果它击中“#34;俄罗斯”这个词就拉一行。"

这是我目前的代码:

import csv
import sys

with open('country.csv', 'rb') as csvfile:
    data = csv.reader(csvfile)
    datalist = []
    for row in data:
        if len (row) != 0:
            datalist = datalist + [row]
csvfile.close()

column_names = datalist[0]  # LIST OF COLUMNS

我怎么去拉整排?

1 个答案:

答案 0 :(得分:1)

尝试filter

>>> filter(lambda x: x[0] == 'Russia', datalist)
[['Russia', '1901', 'Steal'], ['Russia', '1905', 'Gold']]