python - Can I use a Dictionary to store keywords that I need to loop through a csv file to find? -


i writing python script go through csv file row row looking keyword. once keyword found need write entire row new .csv file. having trouble writing loop complete task , not understand how write new .csv file. post have done far below.

#!/usr/bin/python  # first import csv module work on .csv file import csv  #lets open files used read , write infile = open('infile.csv','rb') outfile = open('outfile.csv','w')   # lets pass file object through csv reader method csv_f_reader = csv.reader(infile) writer = csv.writer(outfile,delimiter=',',quotechar='',quoting=csv.quote_none) #lets create dictionary hold search words unique keys. # associated value used keep count of how many successful # hits forloop hits.  search_word={'wifi':0,'wifi':0,'wi-fi':0,'wi-fi':0,'cisco':0,'cisco':0,'netgear':0,'netgear':0,'netge$  csv_line in csv_f_reader:     match_found = false     keyword in search_word.keys():             csv_element in csv_line:                     if keyword in csv_element:                             match_found = true                             search_word[keyword] +=1     if match_found:             writer.writerow(csv_line)   #dont forget close file infile.close() outfile.close() print search_word.keys(), search_word.values() 

you don't need dictionary you're describing (unless you're trying count keyword instances). search_word.keys() gives list anyway ok.

first want iterate through csv this:

infile = open('infile.csv') csv_f_reader = csv.reader(infile) csv_line in csv_f_reader:     print csv_line 

if try that, you'll see each line gives list of elements. can use list of keywords compare each 1 , write ones pass

for csv_line in csv_f_reader:     k in search_word.keys():         if k in csv_line:              writer.writerow(csv_line) 

in case, keywords aren't same csv elements, they're inside them. can deal checking elements substrings:

for csv_line in csv_f_reader:     match_found = false     k in search_word.keys():         csv_element in csv_line:             if k in csv_element:                 match_found = true     if match_found:         writer.writerow(csv_line) 

one other thing, need open output file in write mode with:

outfile = open('outfile.csv', 'w')


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -