Skip to content

Instantly share code, notes, and snippets.

@sepulworld
Created February 21, 2014 05:37
Show Gist options
  • Save sepulworld/9129371 to your computer and use it in GitHub Desktop.
Save sepulworld/9129371 to your computer and use it in GitHub Desktop.
keyword_filter action
import csv
import itertools
def base_file(name):
with open(name, 'rU') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)
for row in spamreader:
yield row
def keyword_data(filename, keyword):
'''
example useage from cli:
python watercompanies.py mock_up.csv "Produced Water"
'''
result_file_name = keyword + filename
updated_file = open(result_file_name, 'wb')
keyword_writer = csv.writer(updated_file, delimiter=',')
# this slices out just the headings from source csv
for row in itertools.islice(base_file(filename), 1):
keyword_writer.writerow(row)
# now grab row if 3rd column (starting from 0) contains keyword value and write to new csv
for row in base_file(filename):
if keyword in row[3]:
keyword_writer.writerow(row)
updated_file.close()
if __name__ == "__main__":
import sys
keyword_data(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment