semiflex semiflex - 3 months ago 15
Python Question

Conditionally extracting rows of CSV files?

I have a CSV file that looks like this:

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


I want it to search through the first column and pull a row if it hits the word "Russia."

This is what my code looks like currently:

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


How would I go about pulling the whole row?

Answer

Try filter:

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