coderkid
coderkid

Reputation: 658

Search a csv for a string and save that column

Using pythons csv module, I'm trying to open a CSV file, search it for a specific string

in that file and once found, store that column. This is my way of reading columns now, but I

won't always know the specific column number that I want, so I need to search for a column

name instead.

with open('Work.csv','r') as f:
 reader = csv.reader(f)
 reader.next()
  for row in reader:
    for (i ,v) in enumerate(row):
      columns[i].append(v)

My csv looks like:

Default  Names  
  0        1
  2        3

Upvotes: 1

Views: 1203

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

import csv
columns = []                        #save the columns in this list
with open('myfile.csv','r') as f:
 reader = csv.reader(f, delimiter='\t')
 ind = next(reader).index('Default')   #find the index of 'Default' in the header
 for row in reader:
     columns.append(row[ind])

Upvotes: 2

aar cee
aar cee

Reputation: 249

Create a list from the row and use index function on a list.

For example

a = 'one two three four'.split()

indexNum = a.index('three')

print indexNum # which is 2

Upvotes: 0

Related Questions